FormatHelper.php 45 KB

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