FormatHelper.php 46 KB

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