FormatHelper.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  1. <?php
  2. App::uses('TextHelper', 'View/Helper');
  3. /**
  4. * Format helper with basic html snippets
  5. *
  6. * TODO: make snippets more "css and background image" (instead of inline img links)
  7. * TODO: test cases
  8. *
  9. * 2009-12-31 ms
  10. */
  11. class FormatHelper extends TextHelper {
  12. /**
  13. * Other helpers used by FormHelper
  14. *
  15. * @var array
  16. * @access public
  17. */
  18. public $helpers = array('Html', 'Form', 'Tools.Common', 'Tools.Gravatar', 'Tools.PhpThumb');
  19. /**
  20. * jqueryAccess: {id}Pro, {id}Contra
  21. * 2009-07-24 ms
  22. */
  23. public function thumbs($id, $inactive = false, $inactiveTitle = null) {
  24. $class = 'Active';
  25. $upTitle = __('Zustimmen');
  26. $downTitle = __('Dagegen');
  27. if ($inactive === true) {
  28. $class = 'Inactive';
  29. $upTitle = $downTitle = !empty($inactiveTitle)?$inactiveTitle:__('alreadyVoted');
  30. }
  31. $ret = '<div class="thumbsUpDown">';
  32. $ret .= '<div id="'.$id.'Pro'.$class.'" rel="'.$id.'" class="thumbUp up'.$class.'" title="'.$upTitle.'"></div>';
  33. $ret .= '<div id="'.$id.'Contra'.$class.'" rel="'.$id.'" class="thumbDown down'.$class.'" title="'.$downTitle.'"></div>';
  34. $ret .= '<br class="clear"/>';
  35. $ret .= '</div>';
  36. return $ret;
  37. }
  38. /**
  39. * Display neighbor quicklinks
  40. *
  41. * @param array $neighbors (containing prev and next)
  42. * @param string $field: just field or Model.field syntax
  43. * @param array $options:
  44. * - name: title name: next{Record} (if none is provided, "record" is used - not translated!)
  45. * - slug: true/false (defaults to false)
  46. * - titleField: field or Model.field
  47. */
  48. public function neighbors($neighbors, $field, $options = array()) {
  49. if (mb_strpos($field, '.') !== false) {
  50. $fieldArray = explode('.', $field, 2);
  51. $alias = $fieldArray[0];
  52. $field = $fieldArray[1];
  53. }
  54. if (empty($alias)) {
  55. if (!empty($neighbors['prev'])) {
  56. $modelNames = array_keys($neighbors['prev']);
  57. $alias = $modelNames[0];
  58. } elseif (!empty($neighbors['next'])) {
  59. $modelNames = array_keys($neighbors['next']);
  60. $alias = $modelNames[0];
  61. }
  62. }
  63. if (empty($field)) {
  64. }
  65. $name = 'Record'; # translation further down!
  66. if (!empty($options['name'])) {
  67. $name = ucfirst($options['name']);
  68. }
  69. $prevSlug = $nextSlug = null;
  70. if (!empty($options['slug'])) {
  71. if (!empty($neighbors['prev'])) {
  72. $prevSlug = slug($neighbors['prev'][$alias][$field]);
  73. }
  74. if (!empty($neighbors['next'])) {
  75. $nextSlug = slug($neighbors['next'][$alias][$field]);
  76. }
  77. }
  78. $titleAlias = $alias;
  79. $titleField = $field;
  80. if (!empty($options['titleField'])) {
  81. if (mb_strpos($options['titleField'], '.') !== false) {
  82. $fieldArray = explode('.', $options['titleField'], 2);
  83. $titleAlias = $fieldArray[0];
  84. $titleField = $fieldArray[1];
  85. } else {
  86. $titleField = $options['titleField'];
  87. }
  88. }
  89. if (!isset($options['escape']) || $options['escape'] === false) {
  90. $titleField = h($titleField);
  91. }
  92. $ret = '<div class="nextPrevNavi">';
  93. if (!empty($neighbors['prev'])) {
  94. $url = array($neighbors['prev'][$alias]['id'], $prevSlug);
  95. if (!empty($options['url'])) {
  96. $url += $options['url'];
  97. }
  98. $ret.= $this->Html->link($this->cIcon(ICON_PREV, false).'&nbsp;'.__('prev'.$name), $url, array('escape'=>false, 'title'=>$neighbors['prev'][$titleAlias][$titleField]));
  99. } else {
  100. $ret.= $this->cIcon(ICON_PREV_DISABLED, __('noPrev'.$name)).'&nbsp;'.__('prev'.$name);
  101. }
  102. $ret.= '&nbsp;&nbsp;';
  103. if (!empty($neighbors['next'])) {
  104. $url = array($neighbors['next'][$alias]['id'], $prevSlug);
  105. if (!empty($options['url'])) {
  106. $url += $options['url'];
  107. }
  108. $ret.= $this->Html->link($this->cIcon(ICON_NEXT, false).'&nbsp;'.__('next'.$name), $url, array('escape'=>false, 'title'=>$neighbors['next'][$titleAlias][$titleField]));
  109. } else {
  110. $ret.= $this->cIcon(ICON_NEXT_DISABLED, __('noNext'.$name)).'&nbsp;'.__('next'.$name);
  111. }
  112. $ret .= '</div>';
  113. return $ret;
  114. }
  115. /**
  116. * allows icons to be added on the fly
  117. * NOTE: overriding not allowed by default
  118. * 2009-01-04 ms
  119. */
  120. public function addIcon($name = null, $pic = null, $title = null, $allowOverride = false) {
  121. if ($allowOverride === true || ($allowOverride !==true && !array_key_exists($name, $this->icons))) {
  122. if (!empty($name) && !empty($pic)) {
  123. $this->icons[$name] = array('pic'=>strtolower($pic),'title'=>(!empty($title)?$title:''));
  124. }
  125. }
  126. return false;
  127. }
  128. const GENDER_FEMALE = 2;
  129. const GENDER_MALE = 1;
  130. /**
  131. * //TODO: move to Format
  132. * displays gender icon
  133. * 2009-01-04 ms
  134. */
  135. public function genderIcon($value = null, $type = null) {
  136. $value = (int)$value;
  137. if ($value == self::GENDER_FEMALE) {
  138. $icon = $this->icon('genderFemale', null, null, null, array('class'=>'gender'));
  139. } elseif ($value == self::GENDER_MALE) {
  140. $icon = $this->icon('genderMale', null, null, null, array('class'=>'gender'));
  141. } else {
  142. $icon = $this->icon('genderUnknown', null, null, null, array('class'=>'gender'));
  143. }
  144. return $icon;
  145. }
  146. /**
  147. * //TODO: move to Format?
  148. * returns img from customImgFolder
  149. * @param ARRAY options (ending [default: gif])
  150. * 2009-12-31 ms
  151. */
  152. public function customIcon($folder, $icon = null, $checkExist = false, $options = array(), $attr = array()) {
  153. $attachment = 'default';
  154. $ending = 'gif';
  155. $image = null;
  156. if (!empty($options)) {
  157. if (!empty($options['ending'])) {
  158. $ending = $options['ending'];
  159. }
  160. if (!empty($options['backend'])) {
  161. $attachment = 'backend';
  162. }
  163. }
  164. if (empty($icon)) {
  165. } elseif ($checkExist === true && !file_exists(PATH_CONTENT.$folder.DS.$icon.'.'.$ending)) {
  166. } else {
  167. $image = $icon;
  168. }
  169. if ($image === null) {
  170. return $this->Html->image(IMG_ICONS.'custom'.'/'.$folder.'_'.$attachment.'.'.$ending, $attr);
  171. }
  172. return $this->Html->image(IMG_CONTENT.$folder.'/'.$image.'.'.$ending, $attr);
  173. }
  174. /**
  175. * //TODO: move to Format?
  176. * @param string $icon iso2 code (e.g. 'de' or 'gb')
  177. * 2009-08-28 ms
  178. */
  179. public function countryIcon($icon = null, $returnFalseonFailure = false, $options = array(), $attr = array()) {
  180. $ending = 'gif';
  181. $image = 'unknown';
  182. if ($specific = Configure::read('Country.image_path')) {
  183. $wwwPath = $specific.'/';
  184. $path = PATH_IMAGES. $specific . DS; //.'country_flags'.DS
  185. } else {
  186. $wwwPath = '/tools/img/country_flags/';
  187. $path = App::pluginPath('Tools') . 'webroot' . DS. 'img' . DS . 'country_flags' . DS;
  188. }
  189. if (!empty($options) && is_array($options)) {
  190. if (!empty($options['ending'])) {
  191. $ending = $options['ending'];
  192. }
  193. }
  194. $icon = mb_strtolower($icon);
  195. if (empty($icon)) {
  196. if ($returnFalseonFailure) { return false; }
  197. } elseif (!file_exists($path . $icon . '.' . $ending)) {
  198. //die($path . $icon . '.' . $ending);
  199. trigger_error($path . $icon . '.' . $ending.' missing', E_USER_NOTICE);
  200. if ($returnFalseonFailure) { return false; }
  201. } else {
  202. $image = $icon;
  203. }
  204. return $this->Html->image($wwwPath . $image . '.' . $ending, $attr);
  205. }
  206. /**
  207. * 2011-10-10 ms
  208. */
  209. public function importantIcon($icon, $value) {
  210. $ending = 'gif';
  211. $image = 'default';
  212. if (!empty($value)) {
  213. $image = 'important';
  214. }
  215. return $this->Html->image(IMG_ICONS.$icon.'_'.$image.'.'.$ending);
  216. }
  217. /**
  218. * @param value
  219. * @param array $options
  220. * - max (3/5, defaults to 5)
  221. * - normal: display an icon for normal as well (defaults to false)
  222. * - map: array (manually map values, if you use 1 based values no need for that)
  223. * - title, alt, ...
  224. * @return string $html
  225. * 2012-08-02 ms
  226. */
  227. public function priorityIcon($value, $options = array()) {
  228. $defaults = array(
  229. 'max' => 5,
  230. 'normal' => false,
  231. 'map' => array(),
  232. 'css' => true,
  233. );
  234. $options = array_merge($defaults, $options);
  235. extract($options);
  236. $matching = array(
  237. 1 => 'low',
  238. 2 => 'lower',
  239. 3 => 'normal',
  240. 4 => 'higher',
  241. 5 => 'high'
  242. );
  243. if (!empty($map)) {
  244. $value = $map[$value];
  245. }
  246. if (!$normal && $value == ($max+1)/2) {
  247. return '';
  248. }
  249. if ($max != 5) {
  250. if ($value == 2) {
  251. $value = 3;
  252. } elseif ($value == 3) {
  253. $value = 5;
  254. }
  255. }
  256. $attr = array(
  257. 'class' => 'prio-'.$matching[$value],
  258. 'title' => __('prio'.ucfirst($matching[$value])),
  259. );
  260. if (!$css) {
  261. $attr['alt'] = $matching[$value];
  262. }
  263. $attr = array_merge($attr, array_diff_key($options, $defaults));
  264. if ($css) {
  265. $html = $this->Html->tag('div', '&nbsp;', $attr);
  266. } else {
  267. $icon = 'priority_' . $matching[$value] . '.gif';
  268. $html = $this->Html->image('icons/'.$icon, $attr);
  269. }
  270. return $html;
  271. }
  272. /**
  273. * Quick way of printing default icons (have to be 16px X 16px !!!)
  274. * @param type
  275. * @param title
  276. * @param alt (set to FALSE if no alt is supposed to be shown)
  277. * @param boolean automagic i18n translate [default true = __('xyz')]
  278. * @param options array ('class'=>'','width/height'=>'','onclick=>'') etc
  279. * 2008-12-28 ms
  280. */
  281. public function icon($type, $t = null, $a = null, $translate = null, $options = array()) {
  282. $html='';
  283. # title
  284. if (isset($t) && $t === false) {
  285. $title='';
  286. } elseif (empty($t)) {
  287. } else {
  288. $title=$t;
  289. //$alt=$t; // alt=title as default
  290. }
  291. #alt
  292. if (isset($a) && $a===false) {
  293. $alt='';
  294. } elseif (empty($a)) {
  295. } else {
  296. $alt=$a;
  297. }
  298. if (array_key_exists($type, $this->icons)) {
  299. $pic = $this->icons[$type]['pic'];
  300. $title = (isset($title)?$title:$this->icons[$type]['title']);
  301. $alt = (isset($alt)?$alt:preg_replace('/[^a-zA-Z0-9]/', '', $this->icons[$type]['title']));
  302. if ($translate !== false) {
  303. $title = __($title);
  304. $alt = __($alt);
  305. }
  306. $alt = '['.$alt.']';
  307. } else {
  308. $pic='pixelspace.gif';
  309. $title = '';
  310. $alt = '';
  311. }
  312. $default_options=array('title'=>$title, 'alt'=>$alt, 'class'=>'icon');
  313. //$new_options['onclick']=$options['onclick'];
  314. $new_options= array_merge($default_options, $options);
  315. $html.=$this->Html->image('icons/'.$pic, $new_options);
  316. return $html;
  317. }
  318. /**
  319. * custom Icons
  320. * @param string $icon (constant or filename)
  321. * @param array $options:
  322. * - translate, ...
  323. * @param array $attributes:
  324. * - title, alt, ...
  325. * THE REST IS DEPRECATED
  326. * 2010-03-04 ms
  327. */
  328. public function cIcon($icon, $t=null, $a=null, $translate=true, $options=array()) {
  329. if (is_array($t)) {
  330. $translate = isset($t['translate']) ? $t['translate'] : true;
  331. $options = (array)$a;
  332. $a = isset($t['alt']) ? $t['alt'] : null; # deprecated
  333. $t = isset($t['title']) ? $t['title'] : null; # deprecated
  334. }
  335. $title = (isset($t) ? $t : ucfirst(extractPathInfo('filename', $icon)));
  336. //$alt = (isset($a)?$a:preg_replace('/[^a-zA-Z0-9]/', '', $title));
  337. $alt = (isset($a) ? $a : Inflector::slug($title, '-'));
  338. if ($translate !== false) {
  339. $title = __($title);
  340. $alt = __($alt);
  341. }
  342. $alt = '['.$alt.']';
  343. $defaultOptions = array('title'=>$title, 'alt'=>$alt, 'class'=>'icon');
  344. $options = array_merge($defaultOptions, $options);
  345. if (substr($icon, 0, 1) !== '/') {
  346. $icon = 'icons/'.$icon;
  347. }
  348. return $this->Html->image($icon, $options);
  349. }
  350. /**
  351. * @deprecated use RatingHelper::stars() instead
  352. * //TODO: move to Format?
  353. * print Star Bar
  354. * array $options: steps=1/0.5 [default:1]), show_zero=true/false [default:false], title=false/true [default:false]
  355. * array $attr: string 'title' (both single and span title empty => 'x of x' for span)
  356. * TODO: 0.5 steps!
  357. * 2009-04-04 ms
  358. */
  359. public function showStars($current = null, $max = null, $options = array(), $attr = array()) {
  360. $res = '---';
  361. if (!empty($options['steps']) && $options['steps'] == 0.5) {
  362. $steps = 0.5;
  363. $current = ((int)(2*$current)/2);
  364. } else {
  365. $steps = 1;
  366. $current = (int)$current;
  367. }
  368. $min = (int)$current;
  369. $max = (int)$max;
  370. if ((!empty($current) || (!empty($options['show_zero']) && $current == 0)) && (!empty($max)) && $current <= $max) {
  371. if (!empty($options) && is_array($options)) {
  372. }
  373. $text = '';
  374. for ($i=0;$i<$min;$i++) {
  375. $attributes = array('alt'=>'#', 'class'=>'full');
  376. if (!empty($options['title'])) { $attributes['title'] = ($i+1).'/'.$max; } # ?
  377. $text.= $this->Html->image('icons/star_icon2.gif', $attributes);
  378. }
  379. for ($i=$min;$i<$max;$i++) {
  380. $attributes = array('alt'=>'-', 'class'=>'empty');
  381. if (!empty($options['title'])) { $attributes['title'] = ($i+1).'/'.$max; } # ?
  382. if ($steps == 0.5 && $current == $i+0.5) {
  383. $text.= $this->Html->image('icons/star_icon2_half.gif', $attributes);
  384. } else {
  385. $text.= $this->Html->image('icons/star_icon2_empty.gif', $attributes);
  386. }
  387. }
  388. $attributes = array('class'=>'starBar');
  389. $attributes = array_merge($attributes, $attr);
  390. if (empty($attributes['title']) && empty($options['title'])) {
  391. $attributes['title'] = ($current) . ' ' . __('of') . ' ' . $max;
  392. }
  393. $res = $this->Html->tag('span', $text, $attributes);
  394. //$res='<span title="ss" class="starBar">'.$text.'</span>';
  395. } else {
  396. if ($max > 3) {
  397. for ($i = 0; $i < $max - 3; $i++) {
  398. $res .= '-';
  399. }
  400. }
  401. }
  402. return $res;
  403. }
  404. /**
  405. * //TODO: move to Format?
  406. * addItemAttribute function
  407. *
  408. * Called to modify the attributes of the next <item> to be processed
  409. * Note that the content of a 'node' is processed before generating its wrapping <item> tag
  410. *
  411. * @param string $id
  412. * @param string $key
  413. * @param mixed $value
  414. * @access public
  415. * @return void
  416. * TODO: refactor!!
  417. */
  418. public function languageFlags() {
  419. $langs = Configure::read('LanguagesAvailable');
  420. $supportedLangs = array(
  421. 'de' => array('title'=>'Deutsch'),
  422. 'en' => array('title'=>'English'),
  423. 'it' => array('title'=>'Italiano'),
  424. );
  425. $language_change = __('Language').': ';
  426. $languages = array();
  427. foreach ($langs as $lang) {
  428. $languages[$lang] = $supportedLangs[$lang];
  429. }
  430. if ($sLang = (string)CakeSession::read('Config.language')) {
  431. $lang = $sLang;
  432. } else {
  433. $lang = '';
  434. }
  435. echo '<span class="country">';
  436. foreach ($languages as $code => $la) {
  437. if ($lang == $code) {
  438. $language_change .= $this->Html->image('language_flags/'.$code.'.gif', array('alt'=>$code,'title'=>$la['title'].' ('.__('active').')','class'=>'country_flag active')).'';
  439. } else {
  440. $language_change .= $this->Html->link($this->Html->image('language_flags/'.$code.'.gif', array('alt'=>$code,'title'=>$la['title'],'class'=>'country_flag')), '/lang/'.$code, array('escape'=>false)).'';
  441. }
  442. }
  443. $language_change .= '</span>'; //.__('(Translation not complete yet)');
  444. return $language_change;
  445. }
  446. /**
  447. * It is still believed that encoding will stop spam-bots being able to find your email address.
  448. * Nevertheless, encoded email address harvester are on the way (http://www.dreamweaverfever.com/experiments/spam/).
  449. *
  450. * //TODO: move to TextExt?
  451. * Helper Function to Obfuscate Email by inserting a span tag (not more! not very secure on its own...)
  452. * each part of this mail now does not make sense anymore on its own
  453. * (striptags will not work either)
  454. * @param string email: necessary (and valid - containing one @)
  455. * 2009-03-11 ms
  456. */
  457. public function encodeEmail($mail) {
  458. list($mail1, $mail2) = explode('@', $mail);
  459. $encMail = $this->encodeText($mail1) . '<span>@</span>' . $this->encodeText($mail2);
  460. return $encMail;
  461. }
  462. /**
  463. * //TODO: move to TextExt?
  464. * Obfuscates Email (works without JS!) to avoid spam bots to get it
  465. * @param string mail: email to encode
  466. * @param string text: optional (if none is given, email will be text as well)
  467. * @param array attributes: html tag attributes
  468. * @param array params: ?subject=y&body=y to be attached to "mailto:xyz"
  469. * @return save string with js generated link around email (and non js fallback)
  470. * 2009-04-20 ms
  471. */
  472. public function encodeEmailUrl($mail, $text = null, $params = array(), $attr = array()) {
  473. if (empty($class)) { $class='email';}
  474. $defaults = array(
  475. 'title'=>__('for use in an external mail client'),
  476. 'class' => 'email',
  477. 'escape' => false
  478. );
  479. if (empty($text)) {
  480. $text = $this->encodeEmail($mail);
  481. }
  482. $encMail = 'mailto:'.$mail;
  483. // additionally there could be a span tag in between: email<span syle="display:none"></span>@web.de
  484. $querystring = '';
  485. foreach ($params as $key=>$val) {
  486. if ($querystring) {
  487. $querystring .= "&$key=" . rawurlencode($val);
  488. } else {
  489. $querystring = "?$key=" . rawurlencode($val);
  490. }
  491. }
  492. $attr = array_merge($defaults, $attr);
  493. $xmail = $this->Html->link('', $encMail . $querystring, $attr);
  494. $xmail1 = mb_substr($xmail, 0, count($xmail) - 5);
  495. $xmail2 = mb_substr($xmail, -4, 4);
  496. $len = mb_strlen($xmail1);
  497. $i=0;
  498. while ($i < $len) {
  499. $c = mt_rand(2, 6);
  500. $par[] = (mb_substr($xmail1, $i, $c));
  501. $i += $c;
  502. }
  503. $join = implode('\'+ \'', $par);
  504. return '<script language=javascript><!--
  505. document.write(\''.$join.'\');
  506. //--></script>
  507. '.$text.'
  508. <script language=javascript><!--
  509. document.write(\''.$xmail2.'\');
  510. //--></script>';
  511. }
  512. /**
  513. * //TODO: move to TextExt?
  514. * Encodes Piece of Text (without usage of JS!) to avoid spam bots to get it
  515. * @param STRING text to encode
  516. * @return string (randomly encoded)
  517. * 2009-03-11 ms
  518. */
  519. public function encodeText($text) {
  520. $encmail = '';
  521. for ($i=0; $i<mb_strlen($text); $i++) {
  522. $encMod = mt_rand(0,2);
  523. switch ($encMod) {
  524. case 0: // None
  525. $encmail .= mb_substr($text, $i,1);
  526. break;
  527. case 1: // Decimal
  528. $encmail .= "&#".ord(mb_substr($text, $i,1)).';';
  529. break;
  530. case 2: // Hexadecimal
  531. $encmail .= "&#x".dechex(ord(mb_substr($text, $i,1))).';';
  532. break;
  533. }
  534. }
  535. return $encmail;
  536. }
  537. /**
  538. * //TODO: move to Format?
  539. * @param text: default FALSE; if TRUE, text instead of the image
  540. * @param ontitle: default FALSE; if it is embadded in a link, set to TRUE
  541. * @return image:Yes/No or text:Yes/No
  542. *
  543. * @todo $on=1, $text=false, $ontitle=false,... => in array(OPTIONS) packen
  544. */
  545. public function yesNo($v, $ontitle=null, $offtitle=null, $on=1, $text=false, $notitle=false) {
  546. $ontitle = (!empty($ontitle)?$ontitle:__('Ja'));
  547. $offtitle = (!empty($offtitle)?$offtitle:__('Nein'));
  548. $sbez = array('0'=>@substr($offtitle, 0, 1), '1'=>@substr($ontitle, 0, 1));
  549. $bez = array('0'=>$offtitle, '1'=>$ontitle);
  550. if ($v==$on) {$icon=ICON_YES; $value=1;} else {$icon=ICON_NO; $value=0;}
  551. if ($text!==false) {
  552. $light=$bez[$value];
  553. } else {
  554. //$light='<img src="images/icons/'.$icon.'" alt="'.$sbez[$value].'" '.($notitle!==false?'title="'.$bez[$value].'"':'').'/>';
  555. //$light=$this->Html->image('',)<img src="images/icons/'.$icon.'" alt="'.$sbez[$value].'" '.($notitle!==false?'title="'.$bez[$value].'"':'').'/>';
  556. $light=$this->Html->image('icons/'.$icon, array('title'=>($ontitle===false?'':$bez[$value]), 'alt'=>$sbez[$value], 'class'=>'icon'));
  557. }
  558. return $light;
  559. }
  560. /**
  561. * get url of a png img of a website (16x16 pixel)
  562. * 2011-02-15 ms
  563. */
  564. public function siteIconUrl($domain) {
  565. if (strpos($domain, 'http') === 0) {
  566. # strip protocol
  567. $pieces = parse_url($domain);
  568. $domain = $pieces['host'];
  569. }
  570. return 'http://www.google.com/s2/favicons?domain='.$domain;
  571. }
  572. /**
  573. * display a png img of a website (16x16 pixel)
  574. * if not available, will return a fallback image (a globe)
  575. * @param domain (preferably without protocol, e.g. "www.site.com")
  576. * 2011-02-15 ms
  577. */
  578. public function siteIcon($domain, $options = array()) {
  579. $url = $this->siteIconUrl($domain);
  580. $options['width'] = 16;
  581. $options['height'] = 16;
  582. if (!isset($options['alt'])) {
  583. $options['alt'] = $domain;
  584. }
  585. if (!isset($options['title'])) {
  586. $options['title'] = $domain;
  587. }
  588. return $this->Html->image($url, $options);
  589. }
  590. /**
  591. * @param string $text
  592. * @param array $options (for generation):
  593. * - inline, font, size, background (optional)
  594. * @param array $tagAttributes (for image)
  595. * @return string $result - as image
  596. * 2010-12-13 ms
  597. */
  598. public function textAsImage($text, $options = array(), $attr = array()) {
  599. /*
  600. $image = new Imagick();
  601. //$image->newImage(218, 46, new ImagickPixel('white'));
  602. $image->setImageCompression(10); // Keine Auswirkung auf Dicke
  603. $draw = new ImagickDraw();
  604. $draw->setFont($font);
  605. $draw->setFontSize(22.0); // Keine Auswirkung auf Dicke
  606. $draw->setFontWeight(100); // 0-999 Keine Auswirkung auf Dicke
  607. $draw->annotation(5, 20, $text);
  608. $image->drawImage($draw);
  609. $image->setImageResolution(1200, 1200); // Keine Auswirkung auf Dicke
  610. $image->setImageFormat('gif');
  611. $image->writeImage(TMP.'x.gif');
  612. $image->trim($mw,0);
  613. */
  614. $defaults = array('alt'=>$text);
  615. $attr = array_merge($defaults, $attr);
  616. return $this->_textAsImage($text, $options, $attr);
  617. }
  618. /**
  619. * @return string $htmlImage tag (or empty string on failure)
  620. * 2010-12-13 ms
  621. */
  622. public function _textAsImage($text, $options = array(), $attr = array()) {
  623. $defaults = array('inline'=>true, 'font' => FILES.'linotype.ttf', 'size'=>18, 'color'=>'#7A7166');
  624. $options = array_merge($defaults, $options);
  625. if ($options['inline']) { # inline base 64 encoded
  626. $folder = CACHE.'imagick';
  627. } else {
  628. $folder = WWW_ROOT.'img'.DS.'content'.DS.'imagick';
  629. }
  630. $file = sha1($text.serialize($options)).'.'.($options['inline'] || !empty($options['background']) ? 'png' : 'gif');
  631. if (!file_exists($folder)) {
  632. mkdir($folder, 0755);
  633. }
  634. if (!file_exists($folder.DS.$file)) {
  635. $command = 'convert -background '.(!empty($options['background'])?'"'.$options['background'].'"':'transparent').' -font '.$options['font'].' -fill '.(!empty($options['color'])?'"'.$options['color'].'"':'transparent').' -pointsize '.$options['size'].' label:"'.$text.'" '.$folder.DS.$file;
  636. exec($command, $a, $r);
  637. if ($r !== 0) {
  638. return '';
  639. }
  640. }
  641. if ($options['inline']) {
  642. $res = file_get_contents($folder.DS.$file);
  643. $out = $this->Html->imageFromBlob($res, $attr);
  644. } else {
  645. $out = $this->Html->image($this->Html->url('/img/content/imagick/', true).$file, $attr);
  646. }
  647. return $out;
  648. }
  649. /**
  650. * 2009-12-24 ms
  651. */
  652. public function disabledLink($text, $options = array()) {
  653. $defaults = array('class' => 'disabledLink', 'title' => __('notAvailable'));
  654. $options = array_merge($defaults, $options);
  655. return $this->Html->tag('span', $text, $options);
  656. }
  657. /**
  658. * display communication action depending on the current rule/right
  659. * 2009-10-14 ms
  660. */
  661. public function action($s) {
  662. //TODO
  663. }
  664. /**
  665. * generate a pagination count: #1 etc for each pagiation record
  666. * respects order (ASC/DESC)
  667. * @param paginator array
  668. * @param count (current post count on this page)
  669. * @param dir (ASC/DESC)
  670. * 2010-12-01 ms
  671. */
  672. public function absolutePaginateCount($paginator, $count, $dir = null) {
  673. if ($dir === null) {
  674. $dir = 'ASC';
  675. }
  676. $currentPage = $paginator['page'];
  677. $pageCount = $paginator['pageCount'];
  678. $totalCount = $paginator['count'];
  679. $limit = $paginator['limit'];
  680. $step = 1; //$paginator['step'];
  681. //pr($paginator);
  682. if ($dir === 'DESC') {
  683. $currentCount = $count + ($pageCount - $currentPage) * $limit * $step;
  684. if ($currentPage != $pageCount && $pageCount > 1) {
  685. $currentCount -= $pageCount * $limit * $step - $totalCount;
  686. }
  687. } else {
  688. $currentCount = $count + ($currentPage-1) * $limit * $step;
  689. }
  690. return $currentCount;
  691. }
  692. /**
  693. * @param float progress
  694. * @param array options:
  695. * - min, max
  696. * - steps
  697. * - decimals (how precise should the result be displayed)
  698. *
  699. * 2010-01-10 ms
  700. */
  701. public function progressBar($progress, $options = array(), $htmlOptions = array()) {
  702. $defaults = array(
  703. 'min' => 0,
  704. 'max' => 100,
  705. 'steps' => 15,
  706. 'decimals' => 1 # TODO: rename to places!!!
  707. );
  708. $options = array_merge($defaults, $options);
  709. $current = (((float)$progress / $options['max']) - $options['min']);
  710. $percent = $current * 100;
  711. $current *= $options['steps'];
  712. $options['progress'] = number_format($current, $options['decimals'], null, '');
  713. $params = Router::queryString($options, array(), true);
  714. App::uses('NumericHelper', 'Tools.View/Helper');
  715. $this->Numeric = new NumericHelper(new View(null));
  716. $htmlDefaults = array('title' => $this->Numeric->format($percent, $options['decimals']) . ' ' . __('Percent'), 'class' => 'help');
  717. $htmlDefaults['alt'] = $htmlDefaults['title'];
  718. $htmlOptions = array_merge($htmlDefaults, $htmlOptions);
  719. //return $this->Html->image('/files/progress_bar/index.php'.$params, $htmlOptions);
  720. # bug in Html::webroot() ??? ommits ?...
  721. return '<img src="' . $this->Html->url('/files') . '/progress_bar/index.php' . $params . '" title="' . $htmlOptions['title'] . '" class="' .
  722. $htmlOptions['class'] . '" alt="' . $htmlOptions['title'] . '" />';
  723. }
  724. public function tip($type, $file, $title, $icon) {
  725. return $this->cIcon($icon, $title, null, null, array('class' => 'tip' . ucfirst($type) . ' hand', 'rel' => $file));
  726. }
  727. public function tipHelp($file) {
  728. return $this->tip('help', $file, 'Hilfe', ICON_HELP);
  729. }
  730. /**
  731. * fixes utf8 problems of native php str_pad function
  732. * @param string $input
  733. * @param int $padLength
  734. * @param string $padString
  735. * @param mixed $padType
  736. * @return string $input
  737. * 2011-09-27 ms
  738. */
  739. public function pad($input, $padLength, $padString, $padType = STR_PAD_RIGHT) {
  740. $length = mb_strlen($input);
  741. if ($padLength - $length > 0) {
  742. switch ($padType) {
  743. case STR_PAD_LEFT:
  744. $input = str_repeat($padString, $padLength-$length).$input;
  745. break;
  746. case STR_PAD_RIGHT:
  747. $input .= str_repeat($padString, $padLength-$length);
  748. break;
  749. }
  750. }
  751. return $input;
  752. }
  753. /**
  754. * deprecated
  755. * album image
  756. * 2009-09-10 ms
  757. */
  758. public function image($id, $options = array(), $attr = array()) {
  759. if (!empty($options['h'])) {
  760. $attr['height'] = $options['h'];
  761. }
  762. if (!empty($options['w'])) {
  763. $attr['width'] = $options['w'];
  764. }
  765. return $this->Html->image($this->imageUrl($id, $options), $attr);
  766. }
  767. public function imageUrl($id, $options = array()) {
  768. return $this->Html->defaultUrl($this->imageUrlArray($id, $options), true);
  769. }
  770. public function imageUrlArray($id, $options = array()) {
  771. $urlArray = array('controller' => 'images', 'action' => 'display', $id);
  772. $urlArray = array_merge($urlArray, $options);
  773. return $urlArray;
  774. }
  775. /**
  776. * album image
  777. * 2009-09-10 ms
  778. */
  779. public function albumImage($image, $options = array(), $attr = array()) {
  780. $subfolder = $image['Album']['id'];
  781. $file = $image['Album']['id'] . DS . $image['Image']['filename'] . '.' . $image['Image']['ext'];
  782. $optionsArray = array(
  783. 'save_path' => WWW_ROOT . 'img'. DS. 'albums' . DS . $subfolder,
  784. 'display_path' => '/img/albums' . '/' . $subfolder,
  785. 'error_image_path' => '/img/userpics/22.jpg',
  786. 'src' => FILES . 'images' . DS . $file,
  787. // From here on out, you can pass any standard phpThumb parameters
  788. 'q' => 100,
  789. 'zc' => 1
  790. );
  791. $options = array_merge($optionsArray, $options);
  792. if (!file_exists($options['save_path'])) {
  793. App::uses('Folder', 'Utility');
  794. $f = new Folder($options['save_path'], true, 0777);
  795. //mkdir($options['save_path'], 0777);
  796. }
  797. $thumbnail = $this->PhpThumb->generate($options);
  798. return $this->Html->image($thumbnail['src'], $attr); //'width' => $thumbnail['w'], 'height' => $thumbnail['h']
  799. }
  800. public function albumImageLink($image, $options = array()) {
  801. $options = array_merge(array('escape' => false), $options);
  802. return $this->Html->defaultLink($this->albumImage($image, array('h' => 50)), $this->imageUrlArray($image['Image']['id'], array('h' => 50)),
  803. $options);
  804. }
  805. public function albumImageTexts($image, $options = array()) {
  806. $display = array(
  807. 'title' => true,
  808. 'description' => true,
  809. 'controls' => true,
  810. 'autoHide' => true
  811. );
  812. if (!isset($image['Album']) && isset($options['album'])) {
  813. $image['Album'] = $options['album'];
  814. }
  815. if ($image['Album']['user_id'] != UID || isset($options['controls']) && $options['controls'] === false) {
  816. $display['controls'] = false;
  817. }
  818. if (isset($options['autoHide']) && $options['autoHide'] === false) {
  819. $display['autoHide'] = false;
  820. }
  821. $res = $controls = $descr = '';
  822. if ($display['title']) { // && (!$display['autoHide'] || !empty($image['Image']['title']))
  823. $defTitle = ($display['autoHide'] ? '' : ': <i>kein Titel</i>');
  824. $title = 'Album \'' . h($image['Album']['title']) . '\'' . (!empty($image['Image']['title']) ? ': ' . h($image['Image']['title']) : $defTitle);
  825. $res .= '<div class="highslide-heading">' . $title . '</div>';
  826. }
  827. $navigation = '<div class="floatRight">&nbsp;' . $this->Html->defaultLink($this->cIcon(ICON_ALBUM, 'Zum Album wechseln'),
  828. array('controller' => 'albums', 'action' => 'view', $image['Album']['id'], slug($image['Album']['title'])), array('escape' => false)) .
  829. '</div>';
  830. if (!empty($image['User']['id'])) {
  831. $gender = '';
  832. if (isset($image['UserInfo']['gender'])) {
  833. $gender = $this->genderIcon($image['UserInfo']['gender']).' ';
  834. }
  835. $navigation .= '<div class="floatRight" style="margin-right: 6px;">'.__('Member').': '.$gender.$this->profileLink($image['User']['id'], $image['User']['username']).'</div>';
  836. }
  837. if ($display['controls']) {
  838. $controls = '<div class="floatRight">&nbsp;' . $this->Html->defaultLink($this->icon('edit'), array('controller' => 'images',
  839. 'action' => 'edit', $image['Image']['id']), array('escape' => false)) . '&nbsp;' . $this->Form->postLink($this->icon('delete'),
  840. array('plugin'=>false, 'admin'=>false, 'controller' => 'images', 'action' => 'delete', $image['Image']['id']), array('escape' => false), 'Sicher?') . '</div>';
  841. }
  842. if ($display['description']) {
  843. $defDescr = ($display['autoHide'] ? '' : '<i>keine Beschreibung</i>');
  844. $descr = (!empty($image['Image']['description']) ? nl2br(h($image['Image']['description'])) : $defDescr);
  845. }
  846. if ($display['controls'] || $display['description']) {
  847. $res .= '<div class="highslide-caption">' . $controls . $navigation . $descr . '</div>';
  848. }
  849. return $res;
  850. }
  851. /**
  852. * takes username + userId and forms a profile link out of it
  853. * if username is empty, return "deleted" text without link
  854. * maybe move to custom/community helper etc?
  855. * 2009-08-27 ms
  856. */
  857. public function profileLink($uid, $username, $text = null, $attr = array(), $options = array()) {
  858. if (empty($username)) {
  859. return '['.__('%s deleted', __('Account')).']';
  860. }
  861. $title = isset($text) ? $text : $username;
  862. $username = slug($username);
  863. $url = array('plugin' => false, 'admin' => false, 'controller' => 'members', 'action' => 'view', $uid, $username);
  864. if (!empty($options['hash'])) {
  865. $url['#'] = $options['hash'];
  866. }
  867. return $this->Html->link($title, $url, $attr);
  868. }
  869. /**
  870. * @param mixed $uid
  871. * @param string $username
  872. * @param bool $full
  873. * @param array $options
  874. * - hash (string)
  875. * @return string $url
  876. * 2011-01-30 ms
  877. */
  878. public function profileUrl($uid, $username, $full = false, $options = array()) {
  879. return $this->Html->url(array('plugin' => false, 'admin' => false, 'controller' => 'members', 'action' => 'view', $uid, slug($username)), $full);
  880. }
  881. /*
  882. public function profileLinkById($uid) {
  883. $username = null; //TODO: get from static list
  884. //$username = slug($username);
  885. return $this->Html->link($username, array('admin'=>false,'controller'=>'members', 'action'=>'view', $uid, $username));
  886. }
  887. */
  888. /**
  889. * better an element?
  890. */
  891. public function profilePic($uid, $e, $rights = null) {
  892. }
  893. /**
  894. * FormatHelper::languageFlag()
  895. *
  896. * @param mixed $iso2
  897. * @param mixed $options
  898. * @return string
  899. */
  900. public function languageFlag($iso2, $options = array()) {
  901. $flag = '';
  902. $defaults = array('alt' => $iso2, 'title' => strtoupper($iso2));
  903. $options = array_merge($defaults, $options);
  904. $flag .= $this->Html->image('language_flags/' . strtolower($iso2) . '.gif', $options);
  905. return $flag;
  906. }
  907. /**
  908. * FormatHelper::countryAndProvince()
  909. *
  910. * @param mixed $array
  911. * @param mixed $options
  912. * @return string
  913. */
  914. public function countryAndProvince($array, $options = array()) {
  915. $res = '<span class="help" title="%s">%s</span>';
  916. $countryTitle = '';
  917. if (!empty($array['Country']['name'])) {
  918. $country = $array['Country']['iso2'];
  919. $countryTitle .= h($array['Country']['name']) . '';
  920. } else {
  921. $country = '';
  922. }
  923. if (!empty($array['CountryProvince']['name'])) {
  924. $countyProvince = h($array['CountryProvince']['abbr']);
  925. $countryTitle .= (!empty($countryTitle) ? ' - ' : '') . h($array['CountryProvince']['name']);
  926. } else {
  927. $countyProvince = '';
  928. $countryTitle .= '';
  929. }
  930. $content = $this->countryIcon($country) . '&nbsp;' . $countyProvince;
  931. $res = sprintf($res, $countryTitle, $content);
  932. return $res;
  933. }
  934. //deprecated?
  935. public function avatar($setting, $uid, $email = null, $options = array()) {
  936. $options = array_merge(array('title' => __('Avatar')), $options);
  937. if ($setting == USER_AVATAR_OWN) {
  938. if (!empty($options['size'])) {
  939. $options['height'] = $options['width'] = $options['size'];
  940. unset($options['size']);
  941. }
  942. return $this->Html->image(IMG_AVATARS . $uid . '.' . AVATAR_ENDING, $options);
  943. } elseif ($setting == USER_AVATAR_GRAV) {
  944. return $this->Gravatar->image($email, $options);
  945. } else {
  946. return $this->Gravatar->image($uid, $options);
  947. }
  948. }
  949. /**
  950. * display traffic light for status etc
  951. * 2008-12-28 ms
  952. */
  953. public function statusLight($color = null, $title = null, $alt = null, $options = array()) {
  954. $icons = array(
  955. 'green', 'yellow', 'red', 'blue'
  956. /*
  957. 'red' => array(
  958. 'title'=>'',
  959. 'alt'=>''
  960. ),
  961. */
  962. );
  963. $icon = (in_array($color, $icons) ? $color : 'blank');
  964. $defaultOptions = array('title' => (!empty($title) ? $title : ucfirst(__('color' . ucfirst($color)))), 'alt' => (!empty($alt) ? $alt :
  965. __('color' . ucfirst($color))), 'class' => 'icon help');
  966. $options = array_merge($defaultOptions, $options);
  967. return $this->Html->image('icons/status_light_' . $icon . '.gif', $options);
  968. }
  969. /**
  970. * FormatHelper::onlineIcon()
  971. *
  972. * @param mixed $modified
  973. * @param mixed $options
  974. * @return string
  975. */
  976. public function onlineIcon($modified = null, $options = array()) {
  977. # from low (off) to high (on)
  978. $icons = array('healthbar0.gif', 'healthbar1.gif', 'healthbar1b.gif', 'healthbar2.gif', 'healthbar3.gif', 'healthbar4.gif', 'healthbar5.gif');
  979. # default = offline
  980. $res = $icons[0]; // inaktiv
  981. $time = strtotime($modified);
  982. $timeAgo = time() - $time; # in seconds
  983. if ($timeAgo < 180) { # 3min // aktiv
  984. $res = $icons[6];
  985. } elseif ($timeAgo < 360) { # 6min
  986. $res = $icons[5];
  987. } elseif ($timeAgo < 540) { # 9min
  988. $res = $icons[4];
  989. } elseif ($timeAgo < 720) { # 12min
  990. $res = $icons[3];
  991. } elseif ($timeAgo < 900) { # 15min
  992. $res = $icons[2];
  993. } elseif ($timeAgo < 1080) { # 18min
  994. $res = $icons[1];
  995. }
  996. return $this->Html->image('misc/' . $res, array('style' => 'width: 60px; height: 16px'));
  997. }
  998. /**
  999. * Returns red colored if not ok
  1000. *
  1001. * @param $okValue
  1002. * @return Value
  1003. */
  1004. public function warning($value, $ok = false) {
  1005. if ($ok !== true) {
  1006. return $this->ok($value, false);
  1007. }
  1008. return $value;
  1009. }
  1010. /**
  1011. * returns green on ok, red otherwise
  1012. * @param mixed $currentValue
  1013. * @param bool $ok: true/false (defaults to false)
  1014. * //@param string $comparizonType
  1015. * //@param mixed $okValue
  1016. * @return string $newValue nicely formatted/colored
  1017. * 2009-08-02 ms
  1018. */
  1019. public function ok($value, $ok = false) {
  1020. if ($ok === true) {
  1021. $value = '<span class="green" style="color:green">' . $value . '</span>';
  1022. } else {
  1023. $value = '<span class="red" style="color:red">' . $value . '</span>';
  1024. }
  1025. return $value;
  1026. }
  1027. /**
  1028. * test@test.de becomes t..t@t..t.de
  1029. * @param string $email: valid(!) email address
  1030. * 2009-08-30 ms
  1031. */
  1032. public static function hideEmail($mail) {
  1033. $mailParts = explode('@', $mail, 2);
  1034. $domainParts = explode('.', $mailParts[1], 2);
  1035. $email = mb_substr($mailParts[0], 0, 1) . '..' . mb_substr($mailParts[0], -1, 1) . '@' . mb_substr($domainParts[0], 0, 1) . '..' . mb_substr($domainParts[0],
  1036. -1, 1) . '.' . $domainParts[1];
  1037. return $email;
  1038. }
  1039. /**
  1040. * (intelligent) Shortening of a text string
  1041. * @param STRING textstring
  1042. * @param INT chars = max-length
  1043. * For options array:
  1044. * @param BOOLEAN strict (default: FALSE = intelligent shortening, cutting only between whole words)
  1045. * @param STRING ending (default: '...' no leading whitespace)
  1046. * @param BOOLEAN remain_lf (default: false = \n to ' ')
  1047. * Note: ONLY If intelligent:
  1048. * - the word supposed to be cut is removed completely (instead of remaining as last one)
  1049. * - Looses line breaks (for textarea content to work with this)!
  1050. * @deprecated use truncate instead
  1051. * 2008-10-30 ms
  1052. */
  1053. public function shortenText($textstring, $chars, $options = array()) {
  1054. $chars++; # add +1 for correct cut
  1055. $needsEnding = false;
  1056. #Options
  1057. $strict = false;
  1058. $ending = CHAR_HELLIP; //'...';
  1059. $remain_lf = false; // not implemented: choose if LF transformed to ' '
  1060. $class = 'help';
  1061. $escape = true;
  1062. $title = '';
  1063. if (!empty($options) && is_array($options)) {
  1064. if (!empty($options['strict']) && ($options['strict'] === true || $options['strict'] === false)) {
  1065. $strict = $options['strict'];
  1066. }
  1067. if (!empty($options['remain_lf']) && ($options['remain_lf'] === true || $options['remain_lf'] === false)) {
  1068. $remain_lf = $options['remain_lf'];
  1069. }
  1070. if (isset($options['title'])) {
  1071. $title = $options['title'];
  1072. if ($options['title'] === true) {
  1073. $title = $textstring;
  1074. }
  1075. }
  1076. if (isset($options['class']) && $options['class'] === false) {
  1077. $class = '';
  1078. }
  1079. if (isset($options['ending'])) {
  1080. $ending = (string )$options['ending'];
  1081. }
  1082. if (isset($options['escape'])) {
  1083. $escape = (bool)$options['escape'];
  1084. }
  1085. }
  1086. $textstring = trim($textstring);
  1087. # cut only between whole words
  1088. if ($strict !== true) {
  1089. $completeWordText = $textstring . ' ';
  1090. # transform line breaks to whitespaces (for textarea content etc.)
  1091. $completeWordTextLf = str_replace(LF, ' ', $completeWordText);
  1092. $completeWordText = $completeWordTextLf;
  1093. $completeWordText = substr($completeWordTextLf, 0, $chars);
  1094. # round the text to the previous entire word instead of cutting off part way through a word
  1095. $completeWordText = substr($completeWordText, 0, strrpos($completeWordText, ' '));
  1096. }
  1097. $textEnding = '';
  1098. if ($strict !== true && strlen($completeWordText) > 1) {
  1099. $text = trim($completeWordText);
  1100. # add ending only if result is shorter then original
  1101. if (strlen($text) < strlen(trim($completeWordTextLf))) {
  1102. $textEnding = ' ' . $ending; # additional whitespace as there is a new word added
  1103. }
  1104. } else {
  1105. $text = trim(substr($textstring, 0, $chars));
  1106. # add ending only if result is shorter then original
  1107. if (strlen($text) < strlen($textstring)) {
  1108. $textEnding = $ending;
  1109. }
  1110. }
  1111. if ($escape) {
  1112. $text = h($text);
  1113. $title = h($title);
  1114. }
  1115. $text .= $textEnding;
  1116. #TitleIfTooLong
  1117. if (!empty($title)) {
  1118. $text = '<span ' . (!empty($class) ? 'class="' . $class . '" ' : '') . 'title="' . $title . '">' . $text . '</span>';
  1119. }
  1120. return $text;
  1121. }
  1122. /**
  1123. *
  1124. * Inspired by the tab2space function found at:
  1125. * @see http://aidan.dotgeek.org/lib/?file=function.tab2space.php
  1126. */
  1127. public function tab2space($text, $spaces = 4) {
  1128. $spaces = str_repeat(" ", $spaces);
  1129. $text = preg_split("/\r\n|\r|\n/", trim($text));
  1130. $word_lengths = array();
  1131. $w_array = array();
  1132. // Store word lengths
  1133. foreach ($text as $line) {
  1134. $words = preg_split("/(\t+)/", $line, -1, PREG_SPLIT_DELIM_CAPTURE);
  1135. foreach (array_keys($words) as $i) {
  1136. $strlen = strlen($words[$i]);
  1137. $add = isset($word_lengths[$i]) && ($word_lengths[$i] < $strlen);
  1138. if ($add || !isset($word_lengths[$i])) {
  1139. $word_lengths[$i] = $strlen;
  1140. }
  1141. }
  1142. $w_array[] = $words;
  1143. }
  1144. // Clear $text
  1145. $text = '';
  1146. // Apply padding when appropriate and rebuild the string
  1147. foreach (array_keys($w_array) as $i) {
  1148. foreach (array_keys($w_array[$i]) as $ii) {
  1149. if (preg_match("/^\t+$/", $w_array[$i][$ii])) {
  1150. $w_array[$i][$ii] = str_pad($w_array[$i][$ii], $word_lengths[$ii], "\t");
  1151. } else {
  1152. $w_array[$i][$ii] = str_pad($w_array[$i][$ii], $word_lengths[$ii]);
  1153. }
  1154. }
  1155. $text .= str_replace("\t", $spaces, implode("", $w_array[$i])) . "\n";
  1156. }
  1157. // Finished
  1158. return $text;
  1159. }
  1160. /**
  1161. * Word Censoring Function
  1162. *
  1163. * Supply a string and an array of disallowed words and any
  1164. * matched words will be converted to #### or to the replacement
  1165. * word you've submitted.
  1166. * @param string the text string
  1167. * @param string the array of censoered words
  1168. * @param string the optional replacement value
  1169. * @return string
  1170. * 2009-11-11 ms
  1171. */
  1172. public function wordCensor($str, $censored, $replacement = null) {
  1173. if (empty($censored)) {
  1174. return $str;
  1175. }
  1176. $str = ' ' . $str . ' ';
  1177. // \w, \b and a few others do not match on a unicode character
  1178. // set for performance reasons. As a result words like ..ber
  1179. // will not match on a word boundary. Instead, we'll assume that
  1180. // a bad word will be bookended by any of these characters.
  1181. $delim = '[-_\'\"`() {}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
  1182. foreach ($censored as $badword) {
  1183. if ($replacement !== null) {
  1184. $str = preg_replace("/({$delim})(" . str_replace('\*', '\w*?', preg_quote($badword, '/')) . ")({$delim})/i", "\\1{$replacement}\\3", $str);
  1185. } else {
  1186. $str = preg_replace("/({$delim})(" . str_replace('\*', '\w*?', preg_quote($badword, '/')) . ")({$delim})/ie", "'\\1'.str_repeat('#', strlen('\\2')).'\\3'",
  1187. $str);
  1188. }
  1189. }
  1190. return trim($str);
  1191. }
  1192. /**
  1193. * Translate a result array into a HTML table
  1194. *
  1195. * @author Aidan Lister <aidan@php.net>
  1196. * @version 1.3.2
  1197. * @link http://aidanlister.com/2004/04/converting-arrays-to-human-readable-tables/
  1198. * @param array $array The result (numericaly keyed, associative inner) array.
  1199. * @param bool $recursive Recursively generate tables for multi-dimensional arrays
  1200. * @param string $null String to output for blank cells
  1201. */
  1202. public function array2table($array, $options = array()) {
  1203. $defaults = array(
  1204. 'null' => '&nbsp;',
  1205. 'recursive' => false,
  1206. 'heading' => true,
  1207. 'escape' => true
  1208. );
  1209. $options = array_merge($defaults, $options);
  1210. // Sanity check
  1211. if (empty($array) || !is_array($array)) {
  1212. return false;
  1213. }
  1214. if (!isset($array[0]) || !is_array($array[0])) {
  1215. $array = array($array);
  1216. }
  1217. // Start the table
  1218. $table = "<table>\n";
  1219. if ($options['heading']) {
  1220. // The header
  1221. $table .= "\t<tr>";
  1222. // Take the keys from the first row as the headings
  1223. foreach (array_keys($array[0]) as $heading) {
  1224. $table .= '<th>' . ($options['escape'] ? h($heading) : $heading) . '</th>';
  1225. }
  1226. $table .= "</tr>\n";
  1227. }
  1228. // The body
  1229. foreach ($array as $row) {
  1230. $table .= "\t<tr>";
  1231. foreach ($row as $cell) {
  1232. $table .= '<td>';
  1233. // Cast objects
  1234. if (is_object($cell)) {
  1235. $cell = (array)$cell;
  1236. }
  1237. if ($options['recursive'] && is_array($cell) && !empty($cell)) {
  1238. // Recursive mode
  1239. $table .= "\n" . self::array2table($cell, $options) . "\n";
  1240. } else {
  1241. $table .= (!is_array($cell) && strlen($cell) > 0) ? ($options['escape'] ? h($cell) : $cell) : $options['null'];
  1242. }
  1243. $table .= '</td>';
  1244. }
  1245. $table .= "</tr>\n";
  1246. }
  1247. $table .= '</table>';
  1248. return $table;
  1249. }
  1250. public $icons = array(
  1251. 'up' => array(
  1252. 'pic'=>ICON_UP,
  1253. 'title'=>'Up',
  1254. ),
  1255. 'down' => array(
  1256. 'pic'=>ICON_DOWN,
  1257. 'title'=>'Down',
  1258. ),
  1259. 'edit' => array(
  1260. 'pic'=>ICON_EDIT,
  1261. 'title'=>'Edit',
  1262. ),
  1263. 'view' => array(
  1264. 'pic'=>ICON_VIEW,
  1265. 'title'=>'View',
  1266. ),
  1267. 'delete' => array(
  1268. 'pic'=>ICON_DELETE,
  1269. 'title'=>'Delete',
  1270. ),
  1271. 'reset' => array(
  1272. 'pic'=>ICON_RESET,
  1273. 'title'=>'Reset',
  1274. ),
  1275. 'help' => array(
  1276. 'pic'=>ICON_HELP,
  1277. 'title'=>'Help',
  1278. ),
  1279. 'loader' => array(
  1280. 'pic'=>'loader.white.gif',
  1281. 'title'=>'Loading...',
  1282. ),
  1283. 'loader-alt' => array(
  1284. 'pic'=>'loader.black.gif',
  1285. 'title'=>'Loading...',
  1286. ),
  1287. 'details' => array(
  1288. 'pic'=>ICON_DETAILS,
  1289. 'title'=>'Details',
  1290. ),
  1291. 'use' => array(
  1292. 'pic'=>ICON_USE,
  1293. 'title'=>'Use',
  1294. ),
  1295. 'yes' => array(
  1296. 'pic'=>ICON_YES,
  1297. 'title'=>'Yes',
  1298. ),
  1299. 'no' => array(
  1300. 'pic'=>ICON_NO,
  1301. 'title'=>'No',
  1302. ),
  1303. # deprecated from here down
  1304. 'close' => array(
  1305. 'pic'=>ICON_CLOCK,
  1306. 'title'=>'Close',
  1307. ),
  1308. 'reply' => array(
  1309. 'pic'=>ICON_REPLY,
  1310. 'title'=>'Reply',
  1311. ),
  1312. 'time' => array(
  1313. 'pic'=>ICON_CLOCK,
  1314. 'title'=>'Time',
  1315. ),
  1316. 'check' => array(
  1317. 'pic'=>ICON_CHECK,
  1318. 'title'=>'Check',
  1319. ),
  1320. 'role' => array(
  1321. 'pic'=>ICON_ROLE,
  1322. 'title'=>'Role',
  1323. ),
  1324. 'add' => array(
  1325. 'pic'=>ICON_ADD,
  1326. 'title'=>'Add',
  1327. ),
  1328. 'remove' => array(
  1329. 'pic'=>ICON_REMOVE,
  1330. 'title'=>'Remove',
  1331. ),
  1332. 'email' => array(
  1333. 'pic'=>ICON_EMAIL,
  1334. 'title'=>'Email',
  1335. ),
  1336. 'options' => array(
  1337. 'pic'=>ICON_SETTINGS,
  1338. 'title'=>'Options',
  1339. ),
  1340. 'lock' => array(
  1341. 'pic'=>ICON_LOCK,
  1342. 'title'=>'Locked',
  1343. ),
  1344. 'warning' => array(
  1345. 'pic'=>ICON_WARNING,
  1346. 'title'=>'Warning',
  1347. ),
  1348. 'genderUnknown' => array(
  1349. 'pic'=>'gender_icon.gif',
  1350. 'title'=>'genderUnknown',
  1351. ),
  1352. 'genderMale' => array(
  1353. 'pic'=>'gender_icon_m.gif',
  1354. 'title'=>'genderMale',
  1355. ),
  1356. 'genderFemale' => array(
  1357. 'pic'=>'gender_icon_f.gif',
  1358. 'title'=>'genderFemale',
  1359. ),
  1360. );
  1361. }
  1362. # default icons
  1363. if (!defined('ICON_UP')) {
  1364. define('ICON_UP', 'up.gif');
  1365. }
  1366. if (!defined('ICON_DOWN')) {
  1367. define('ICON_DOWN', 'down.gif');
  1368. }
  1369. if (!defined('ICON_EDIT')) {
  1370. define('ICON_EDIT', 'edit.gif');
  1371. }
  1372. if (!defined('ICON_VIEW')) {
  1373. define('ICON_VIEW', 'see.gif');
  1374. }
  1375. if (!defined('ICON_DELETE')) {
  1376. define('ICON_DELETE', 'delete.gif');
  1377. }
  1378. if (!defined('ICON_DETAILS')) {
  1379. define('ICON_DETAILS', 'loupe.gif');
  1380. }
  1381. if (!defined('ICON_OPTIONS')) {
  1382. define('ICON_OPTIONS', 'options.gif');
  1383. }
  1384. if (!defined('ICON_SETTINGS')) {
  1385. define('ICON_SETTINGS', 'options.gif');
  1386. }
  1387. if (!defined('ICON_USE')) {
  1388. define('ICON_USE', 'use.gif');
  1389. }
  1390. if (!defined('ICON_CLOSE')) {
  1391. define('ICON_CLOSE', 'close.gif');
  1392. }
  1393. if (!defined('ICON_REPLY')) {
  1394. define('ICON_REPLY', 'reply.gif');
  1395. }
  1396. if (!defined('ICON_RESET')) {
  1397. define('ICON_RESET', 'reset.gif');
  1398. }
  1399. if (!defined('ICON_HELP')) {
  1400. define('ICON_HELP', 'help.gif');
  1401. }
  1402. if (!defined('ICON_YES')) {
  1403. define('ICON_YES', 'yes.gif');
  1404. }
  1405. if (!defined('ICON_NO')) {
  1406. define('ICON_NO', 'no.gif');
  1407. }
  1408. if (!defined('ICON_CLOCK')) {
  1409. define('ICON_CLOCK', 'clock.gif');
  1410. }
  1411. if (!defined('ICON_CHECK')) {
  1412. define('ICON_CHECK', 'check.gif');
  1413. }
  1414. if (!defined('ICON_ROLE')) {
  1415. define('ICON_ROLE', 'role.gif');
  1416. }
  1417. if (!defined('ICON_ADD')) {
  1418. define('ICON_ADD', 'add.gif');
  1419. }
  1420. if (!defined('ICON_REMOVE')) {
  1421. define('ICON_REMOVE', 'remove.gif');
  1422. }
  1423. if (!defined('ICON_EMAIL')) {
  1424. define('ICON_EMAIL', 'email.gif');
  1425. }
  1426. if (!defined('ICON_LOCK')) {
  1427. define('ICON_LOCK', 'lock.gif');
  1428. }
  1429. if (!defined('ICON_WARNING')) {
  1430. define('ICON_WARNING', 'warning.png');
  1431. }
  1432. if (!defined('ICON_MAP')) {
  1433. define('ICON_MAP', 'map.gif');
  1434. }