FormatHelper.php 46 KB

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