dolibarr  20.0.0-beta
Functions | Variables
functions.lib.php File Reference

A set of functions for Dolibarr This file contains all frequently used functions. More...

Go to the source code of this file.

Functions

if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists('str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists('str_contains')) getMultidirOutput ($object, $module='', $forobject=0, $mode='output')
 Return the full path of the directory where a module (or an object of a module) stores its files, Path may depends on the entity if a multicompany module is enabled. More...
 
 getMultidirTemp ($object, $module='', $forobject=0)
 Return the full path of the directory where a module (or an object of a module) stores its temporary files. More...
 
 getMultidirVersion ($object, $module='', $forobject=0)
 Return the full path of the directory where a module (or an object of a module) stores its versioned files. More...
 
 getDolGlobalString ($key, $default='')
 Return dolibarr global constant string value. More...
 
 getDolGlobalInt ($key, $default=0)
 Return a Dolibarr global constant int value. More...
 
 getDolUserString ($key, $default='', $tmpuser=null)
 Return Dolibarr user constant string value. More...
 
 getDolUserInt ($key, $default=0, $tmpuser=null)
 Return Dolibarr user constant int value. More...
 
 isModEnabled ($module)
 Is Dolibarr module enabled. More...
 
 isDolTms ($timestamp)
 isDolTms check if a timestamp is valid. More...
 
 getDoliDBInstance ($type, $host, $user, $pass, $name, $port)
 Return a DoliDB instance (database handler). More...
 
 getEntity ($element, $shared=1, $currentobject=null)
 Get list of entity id to use. More...
 
 setEntity ($currentobject)
 Set entity id to use when to create an object. More...
 
 isASecretKey ($keyname)
 Return if string has a name dedicated to store a secret. More...
 
 num2Alpha ($n)
 Return a numeric value into an Excel like column number. More...
 
 getBrowserInfo ($user_agent)
 Return information about user browser. More...
 
 dol_shutdown ()
 Function called at end of web php process. More...
 
 GETPOSTISSET ($paramname)
 Return true if we are in a context of submitting the parameter $paramname from a POST of a form. More...
 
 GETPOSTISARRAY ($paramname, $method=0)
 Return true if the parameter $paramname is submit from a POST OR GET as an array. More...
 
 GETPOST ($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
 Return value of a param into GET or POST supervariable. More...
 
 GETPOSTINT ($paramname, $method=0)
 Return the value of a $_GET or $_POST supervariable, converted into integer. More...
 
 GETPOSTFLOAT ($paramname, $rounding='')
 Return the value of a $_GET or $_POST supervariable, converted into float. More...
 
 checkVal ($out='', $check='alphanohtml', $filter=null, $options=null)
 Return a sanitized or empty value after checking value against a rule. More...
 
 sanitizeVal ($out='', $check='alphanohtml', $filter=null, $options=null)
 Return a sanitized or empty value after checking value against a rule. More...
 
if(!function_exists('dol_getprefix')) dol_include_once ($relpath, $classname='')
 Make an include_once using default root and alternate root if it fails. More...
 
 dol_buildpath ($path, $type=0, $returnemptyifnotfound=0)
 Return path of url or filesystem. More...
 
 dol_get_object_properties ($obj, $properties=[])
 Get properties for an object - including magic properties when requested. More...
 
 dol_clone ($object, $native=0)
 Create a clone of instance of object (new instance with same value for each properties) With native = 0: Property that are references are different memory area in the new object (full isolation clone). More...
 
 dol_size ($size, $type='')
 Optimize a size for some browsers (phone, smarphone, ...) More...
 
 dol_sanitizeFileName ($str, $newstr='_', $unaccent=1)
 Clean a string to use it as a file name. More...
 
 dol_sanitizePathName ($str, $newstr='_', $unaccent=1)
 Clean a string to use it as a path name. More...
 
 dol_sanitizeUrl ($stringtoclean, $type=1)
 Clean a string to use it as an URL (into a href or src attribute) More...
 
 dol_sanitizeEmail ($stringtoclean)
 Clean a string to use it as an Email. More...
 
 dol_string_unaccent ($str)
 Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName. More...
 
 dol_string_nospecial ($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
 Clean a string from all punctuation characters to use it as a ref or login. More...
 
 dol_string_nounprintableascii ($str, $removetabcrlf=1)
 Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). More...
 
 dol_escape_js ($stringtoescape, $mode=0, $noescapebackslashn=0)
 Returns text escaped for inclusion into javascript code. More...
 
 dol_escape_json ($stringtoescape)
 Returns text escaped for inclusion into javascript code. More...
 
 dol_escape_php ($stringtoescape, $stringforquotes=2)
 Returns text escaped for inclusion into a php string, build with double quotes " or '. More...
 
 dol_escape_xml ($stringtoescape)
 Returns text escaped for inclusion into a XML string. More...
 
 dolPrintLabel ($s)
 Return a string label (so on 1 line only and that should not contains any HTML) ready to be output on HTML page To use text that is not HTML content inside an attribute, use can simply only dol_escape_htmltag(). More...
 
 dolPrintHTML ($s, $allowiframe=0)
 Return a string (that can be on several lines) ready to be output on a HTML page. More...
 
 dolPrintHTMLForAttribute ($s)
 Return a string ready to be output on an HTML attribute (alt, title, data-html, ...) More...
 
 dolPrintHTMLForTextArea ($s, $allowiframe=0)
 Return a string ready to be output on input textarea. More...
 
 dolPrintPassword ($s)
 Return a string ready to be output on an HTML attribute (alt, title, ...) More...
 
 dol_escape_htmltag ($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
 Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input fields. More...
 
 dol_strtolower ($string, $encoding="UTF-8")
 Convert a string to lower. More...
 
 dol_strtoupper ($string, $encoding="UTF-8")
 Convert a string to upper. More...
 
 dol_ucfirst ($string, $encoding="UTF-8")
 Convert first character of the first word of a string to upper. More...
 
 dol_ucwords ($string, $encoding="UTF-8")
 Convert first character of all the words of a string to upper. More...
 
 dol_syslog ($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
 Write log message into outputs. More...
 
 dolButtonToOpenExportDialog ($name, $label, $buttonstring, $exportSiteName, $overwriteGitUrl, $website)
 Create a dialog with two buttons for export and overwrite of a website. More...
 
 dolButtonToOpenUrlInDialogPopup ($name, $label, $buttonstring, $url, $disabled='', $morecss='classlink button bordertransp', $jsonopen='', $backtopagejsfields='', $accesskey='')
 Return HTML code to output a button to open a dialog popup box. More...
 
 dol_fiche_head ($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='')
 Show tab header of a card. More...
 
 dol_get_fiche_head ($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0)
 Show tabs of a record. More...
 
 dol_fiche_end ($notab=0)
 Show tab footer of a card. More...
 
 dol_get_fiche_end ($notab=0)
 Return tab footer of a card. More...
 
 fieldLabel ($langkey, $fieldkey, $fieldrequired=0)
 Show a string with the label tag dedicated to the HTML edit field. More...
 
 dol_bc ($var, $moreclass='')
 Return string to add class property on html element with pair/impair. More...
 
 dol_format_address ($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
 Return a formatted address (part address/zip/town/state) according to country rules. More...
 
 dol_strftime ($fmt, $ts=false, $is_gmt=false)
 Format a string. More...
 
 dol_print_date ($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
 Output date in a string format according to outputlangs (or langs if not defined). More...
 
 dol_getdate ($timestamp, $fast=false, $forcetimezone='')
 Return an array with locale date info. More...
 
 dol_mktime ($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
 Return a timestamp date built from detailed information (by default a local PHP server timestamp) Replace function mktime not available under Windows if year < 1970 PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows. More...
 
 dol_now ($mode='auto')
 Return date for now. More...
 
 dol_print_size ($size, $shortvalue=0, $shortunit=0)
 Return string with formatted size. More...
 
 dol_print_url ($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
 Show Url link. More...
 
 dol_print_email ($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0)
 Show EMail link formatted for HTML output. More...
 
 getArrayOfSocialNetworks ()
 Get array of social network dictionary. More...
 
 dol_print_socialnetworks ($value, $cid, $socid, $type, $dictsocialnetworks=array())
 Show social network link. More...
 
 dol_print_profids ($profID, $profIDtype, $countrycode='', $addcpButton=1)
 Format professional IDs according to their country. More...
 
 dol_print_phone ($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0)
 Format phone numbers according to country. More...
 
 dol_print_ip ($ip, $mode=0)
 Return an IP formatted to be shown on screen. More...
 
 getUserRemoteIP ()
 Return the IP of remote user. More...
 
 isHTTPS ()
 Return if we are using a HTTPS connection Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy) Take HTTP_X_FORWARDED_PROTO (defined when using proxy) Then HTTP_X_FORWARDED_SSL. More...
 
 dolGetCountryCodeFromIp ($ip)
 Return a country code from IP. More...
 
 dol_user_country ()
 Return country code for current user. More...
 
 dol_print_address ($address, $htmlid, $element, $id, $noprint=0, $charfornl='')
 Format address string. More...
 
 isValidEmail ($address, $acceptsupervisorkey=0, $acceptuserkey=0)
 Return true if email syntax is ok. More...
 
 isValidMXRecord ($domain)
 Return if the domain name has a valid MX record. More...
 
 isValidPhone ($phone)
 Return true if phone number syntax is ok TODO Decide what to do with this. More...
 
 dolGetFirstLetters ($s, $nbofchar=1)
 Return first letters of a strings. More...
 
 dol_strlen ($string, $stringencoding='UTF-8')
 Make a strlen call. More...
 
 dol_substr ($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
 Make a substring. More...
 
 dol_trunc ($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
 Truncate a string to a particular length adding '…' if string larger than length. More...
 
 getPictoForType ($key, $morecss='')
 Return the picto for a data type. More...
 
 img_picto ($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
 Show picto whatever it's its name (generic function) More...
 
 img_object ($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
 Show a picto called object_picto (generic function) More...
 
 img_weather ($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $morecss='')
 Show weather picto. More...
 
 img_picto_common ($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $notitle=0)
 Show picto (generic function) More...
 
 img_action ($titlealt, $numaction, $picto='', $moreatt='')
 Show logo action. More...
 
 img_pdf ($titlealt='default', $size=3)
 Show pdf logo. More...
 
 img_edit_add ($titlealt='default', $other='')
 Show logo +. More...
 
 img_edit_remove ($titlealt='default', $other='')
 Show logo -. More...
 
 img_edit ($titlealt='default', $float=0, $other='')
 Show logo edit/modify fiche. More...
 
 img_view ($titlealt='default', $float=0, $other='class="valignmiddle"')
 Show logo view card. More...
 
 img_delete ($titlealt='default', $other='class="pictodelete"', $morecss='')
 Show delete logo. More...
 
 img_printer ($titlealt="default", $other='')
 Show printer logo. More...
 
 img_split ($titlealt='default', $other='class="pictosplit"')
 Show split logo. More...
 
 img_help ($usehelpcursor=1, $usealttitle=1)
 Show help logo with cursor "?". More...
 
 img_info ($titlealt='default')
 Show info logo. More...
 
 img_warning ($titlealt='default', $moreatt='', $morecss='pictowarning')
 Show warning logo. More...
 
 img_error ($titlealt='default')
 Show error logo. More...
 
 img_next ($titlealt='default', $moreatt='')
 Show next logo. More...
 
 img_previous ($titlealt='default', $moreatt='')
 Show previous logo. More...
 
 img_down ($titlealt='default', $selected=0, $moreclass='')
 Show down arrow logo. More...
 
 img_up ($titlealt='default', $selected=0, $moreclass='')
 Show top arrow logo. More...
 
 img_left ($titlealt='default', $selected=0, $moreatt='')
 Show left arrow logo. More...
 
 img_right ($titlealt='default', $selected=0, $moreatt='')
 Show right arrow logo. More...
 
 img_allow ($allow, $titlealt='default')
 Show tick logo if allowed. More...
 
 img_credit_card ($brand, $morecss=null)
 Return image of a credit card according to its brand name. More...
 
 img_mime ($file, $titlealt='', $morecss='')
 Show MIME img of a file. More...
 
 img_search ($titlealt='default', $other='')
 Show search logo. More...
 
 img_searchclear ($titlealt='default', $other='')
 Show search logo. More...
 
 info_admin ($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='')
 Show information in HTML for admin users or standard users. More...
 
 dol_print_error ($db=null, $error='', $errors=null)
 Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs. More...
 
 dol_print_error_email ($prefixcode, $errormessage='', $errormessages=array(), $morecss='error', $email='')
 Show a public email and error code to contact if technical error. More...
 
 print_liste_field_titre ($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
 Show title line of an array. More...
 
 getTitleFieldOfList ($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $disablesortlink=0, $tooltip='', $forcenowrapcolumntitle=0)
 Get title line of an array. More...
 
 print_titre ($title)
 Show a title. More...
 
 print_fiche_titre ($title, $mesg='', $picto='generic', $pictoisfullpath=0, $id='')
 Show a title with picto. More...
 
 load_fiche_titre ($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
 Load a title with picto. More...
 
 print_barre_liste ($title, $page, $file, $options='', $sortfield='', $sortorder='', $morehtmlcenter='', $num=-1, $totalnboflines='', $picto='generic', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limit=-1, $hideselectlimit=0, $hidenavigation=0, $pagenavastextinput=0, $morehtmlrightbeforearrow='')
 Print a title with navigation controls for pagination. More...
 
 print_fleche_navigation ($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0, $beforearrows='', $hidenavigation=0)
 Function to show navigation arrows into lists. More...
 
 vatrate ($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
 Return a string with VAT rate label formatted for view output Used into pdf and HTML pages. More...
 
 price ($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
 Function to format a value into an amount for visual output Function used into PDF and HTML pages. More...
 
 price2num ($amount, $rounding='', $option=0)
 Function that return a number with universal decimal format (decimal separator is '. More...
 
 showDimensionInBestUnit ($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no', $use_short_label=0)
 Output a dimension with best unit. More...
 
 get_localtax ($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
 Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller Note: This function applies same rules than get_default_tva. More...
 
 isOnlyOneLocalTax ($local)
 Return true if LocalTax (1 or 2) is unique. More...
 
 get_localtax_by_third ($local)
 Get values of localtaxes (1 or 2) for company country for the common vat with the highest value. More...
 
 getTaxesFromId ($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
 Get tax (VAT) main information from Id. More...
 
 getLocalTaxesFromRate ($vatrate, $local, $buyer, $seller, $firstparamisid=0)
 Get type and rate of localtaxes for a particular vat rate/country of a thirdparty. More...
 
 get_product_vat_for_country ($idprod, $thirdpartytouse, $idprodfournprice=0)
 Return vat rate of a product in a particular country, or default country vat if product is unknown. More...
 
 get_product_localtax_for_country ($idprod, $local, $thirdpartytouse)
 Return localtax vat rate of a product in a particular country or default country vat if product is unknown. More...
 
 get_default_tva (Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
 Function that return vat rate of a product line (according to seller, buyer and product vat rate) VATRULE 1: If seller does not use VAT, default VAT is 0. More...
 
 get_default_npr (Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
 Function that returns whether VAT must be recoverable collected VAT (e.g. More...
 
 get_default_localtax ($thirdparty_seller, $thirdparty_buyer, $local, $idprod=0)
 Function that return localtax of a product line (according to seller, buyer and product vat rate) If the seller is not subject to VAT, then default VAT=0. More...
 
 yn ($yesno, $case=1, $color=0)
 Return yes or no in current language. More...
 
 get_exdir ($num, $level, $alpha, $withoutslash, $object, $modulepart='')
 Return a path to have a the directory according to object where files are stored. More...
 
 dol_mkdir ($dir, $dataroot='', $newmask='')
 Creation of a directory (this can create recursive subdir) More...
 
 dolChmod ($filepath, $newmask='')
 Change mod of a file. More...
 
 picto_required ()
 Return picto saying a field is required. More...
 
 dol_string_nohtmltag ($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
 Clean a string from all HTML tags and entities. More...
 
 dol_string_onlythesehtmltags ($stringtoclean, $cleanalsosomestyles=1, $removeclassattribute=1, $cleanalsojavascript=0, $allowiframe=0, $allowed_tags=array(), $allowlink=0)
 Clean a string to keep only desirable HTML tags. More...
 
 dol_string_onlythesehtmlattributes ($stringtoclean, $allowed_attributes=null)
 Clean a string from some undesirable HTML tags. More...
 
 dol_string_neverthesehtmltags ($stringtoclean, $disallowed_tags=array('textarea'), $cleanalsosomestyles=0)
 Clean a string from some undesirable HTML tags. More...
 
 dolGetFirstLineOfText ($text, $nboflines=1, $charset='UTF-8')
 Return first line of text. More...
 
 dol_nl2br ($stringtoencode, $nl2brmode=0, $forxml=false)
 Replace CRLF in string with a HTML BR tag. More...
 
 dol_htmlwithnojs ($stringtoencode, $nouseofiframesandbox=0, $check='restricthtml')
 Sanitize a HTML to remove js, dangerous content and external link. More...
 
 dol_htmlentitiesbr ($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
 This function is called to encode a string into a HTML string but differs from htmlentities because a detection is done before to see if text is already HTML or not. More...
 
 dol_htmlentitiesbr_decode ($stringtodecode, $pagecodeto='UTF-8')
 This function is called to decode a HTML string (it decodes entities and br tags) More...
 
 dol_htmlcleanlastbr ($stringtodecode)
 This function remove all ending
and br at end. More...
 
 dol_html_entity_decode ($a, $b, $c='UTF-8', $keepsomeentities=0)
 Replace html_entity_decode functions to manage errors. More...
 
 dol_htmlentities ($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
 Replace htmlentities functions. More...
 
 dol_string_is_good_iso ($s, $clean=0)
 Check if a string is a correct iso string If not, it will not be considered as HTML encoded even if it is by FPDF. More...
 
 dol_nboflines ($s, $maxchar=0)
 Return nb of lines of a clear text. More...
 
 dol_nboflines_bis ($text, $maxlinesize=0, $charset='UTF-8')
 Return nb of lines of a formatted text with
and
(WARNING: string must not have mixed
and br separators) More...
 
 dol_textishtml ($msg, $option=0)
 Return if a text is a html content. More...
 
 dol_concatdesc ($text1, $text2, $forxml=false, $invert=false)
 Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator) text1 html + text2 html => text1 + '
' + text2 text1 html + text2 txt => text1 + '
' + dol_nl2br(text2) text1 txt + text2 html => dol_nl2br(text1) + '
' + text2 text1 txt + text2 txt => text1 + '
' + text2. More...
 
 getCommonSubstitutionArray ($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
 Return array of possible common substitutions. More...
 
 make_substitutions ($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
 Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval), and texts like __(TranslationKey|langfile)__ and [ConstantKey] are also replaced. More...
 
 complete_substitutions_array (&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
 Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array. More...
 
 print_date_range ($date_start, $date_end, $format='', $outputlangs=null)
 Format output for start and end date. More...
 
 get_date_range ($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
 Format output for start and end date. More...
 
 dolGetFirstLastname ($firstname, $lastname, $nameorder=-1)
 Return firstname and lastname in correct order. More...
 
 setEventMessage ($mesgs, $style='mesgs', $noduplicate=0)
 Set event message in dol_events session object. More...
 
 setEventMessages ($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
 Set event messages in dol_events session object. More...
 
 dol_htmloutput_events ($disabledoutputofmessages=0)
 Print formatted messages to output (Used to show messages on html output). More...
 
 get_htmloutput_mesg ($mesgstring='', $mesgarray=[], $style='ok', $keepembedded=0)
 Get formatted messages to output (Used to show messages on html output). More...
 
 get_htmloutput_errors ($mesgstring='', $mesgarray=array(), $keepembedded=0)
 Get formatted error messages to output (Used to show messages on html output). More...
 
 dol_htmloutput_mesg ($mesgstring='', $mesgarray=array(), $style='ok', $keepembedded=0)
 Print formatted messages to output (Used to show messages on html output). More...
 
 dol_htmloutput_errors ($mesgstring='', $mesgarray=array(), $keepembedded=0)
 Print formatted error messages to output (Used to show messages on html output). More...
 
 dol_sort_array (&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
 Advanced sort array by the value of a given key, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well). More...
 
 utf8_check ($str)
 Check if a string is in UTF8. More...
 
 utf8_valid ($str)
 Check if a string is in UTF8. More...
 
 ascii_check ($str)
 Check if a string is in ASCII. More...
 
 dol_osencode ($str)
 Return a string encoded into OS filesystem encoding. More...
 
 dol_getIdFromCode ($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
 Return an id or code from a code or id. More...
 
 isStringVarMatching ($var, $regextext, $matchrule=1)
 Check if a variable with name $var startx with $text. More...
 
 verifCond ($strToEvaluate, $onlysimplestring='1')
 Verify if condition in string is ok or not. More...
 
 dol_eval ($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
 Replace eval function to add more security. More...
 
 dol_validElement ($element)
 Return if var element is ok. More...
 
 picto_from_langcode ($codelang, $moreatt='', $notitlealt=0)
 Return img flag of country for a language code or country code. More...
 
 getLanguageCodeFromCountryCode ($countrycode)
 Return default language from country code. More...
 
 complete_head_from_modules ($conf, $langs, $object, &$head, &$h, $type, $mode='add', $filterorigmodule='')
 Complete or removed entries into a head array (used to build tabs). More...
 
 printCommonFooter ($zone='private')
 Print common footer : conf->global->MAIN_HTML_FOOTER js for switch of menu hider js for conf->global->MAIN_GOOGLE_AN_ID js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"] js for conf->logbuffer. More...
 
 dolExplodeIntoArray ($string, $delimiter=';', $kv='=')
 Split a string with 2 keys into key array. More...
 
 dol_set_focus ($selector)
 Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag) More...
 
 dol_getmypid ()
 Return getmypid() or random PID when function is disabled Some web hosts disable this php function for security reasons and sometimes we can't redeclare function. More...
 
 natural_search ($fields, $value, $mode=0, $nofirstand=0)
 Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields) More...
 
 showDirectDownloadLink ($object)
 Return string with full Url. More...
 
 getImageFileNameForSize ($file, $extName, $extImgTarget='')
 Return the filename of file to get the thumbs. More...
 
 getAdvancedPreviewUrl ($modulepart, $relativepath, $alldata=0, $param='')
 Return URL we can use for advanced preview links. More...
 
 ajax_autoselect ($htmlname, $addlink='', $textonlink='Link')
 Make content of an input box selected when we click into input field. More...
 
 dolIsAllowedForPreview ($file)
 Return if a file is qualified for preview. More...
 
 dol_mimetype ($file, $default='application/octet-stream', $mode=0)
 Return MIME type of a file from its name with extension. More...
 
 getDictionaryValue ($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
 Return the value of a filed into a dictionary for the record $id. More...
 
 colorIsLight ($stringcolor)
 Return true if the color is light. More...
 
 isVisibleToUserType ($type_user, &$menuentry, &$listofmodulesforexternal)
 Function to test if an entry is enabled or not. More...
 
 roundUpToNextMultiple ($n, $x=5)
 Round to next multiple. More...
 
 dolGetBadge ($label, $html='', $type='primary', $mode='', $url='', $params=array())
 Function dolGetBadge. More...
 
 dolGetStatus ($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
 Output the badge of a status. More...
 
 dolGetButtonAction ($label, $text='', $actionType='default', $url='', $id='', $userRight=1, $params=array())
 Function dolGetButtonAction. More...
 
 dolGetButtonTitleSeparator ($moreClass="")
 Add space between dolGetButtonTitle. More...
 
 getFieldErrorIcon ($fieldValidationErrorMsg)
 get field error icon More...
 
 dolGetButtonTitle ($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
 Function dolGetButtonTitle : this kind of buttons are used in title in list. More...
 
 getElementProperties ($elementType)
 Get an array with properties of an element. More...
 
 fetchObjectByElement ($element_id, $element_type, $element_ref='', $useCache=0, $maxCacheByType=10)
 Fetch an object from its id and element_type Inclusion of classes is automatic. More...
 
 isAFileWithExecutableContent ($filename)
 Return if a file can contains executable content. More...
 
 newToken ()
 Return the value of token currently saved into session with name 'newtoken'. More...
 
 currentToken ()
 Return the value of token currently saved into session with name 'token'. More...
 
 getNonce ()
 Return a random string to be used as a nonce value for js. More...
 
 startSimpleTable ($header, $link="", $arguments="", $emptyColumns=0, $number=-1, $pictofulllist='')
 Start a table with headers and a optional clickable number (don't forget to use "finishSimpleTable()" after the last table row) More...
 
 finishSimpleTable ($addLineBreak=false)
 Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line) More...
 
 addSummaryTableLine ($tableColumnCount, $num, $nbofloop=0, $total=0, $noneWord="None", $extraRightColumn=false)
 Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx") More...
 
 readfileLowMemory ($fullpath_original_file_osencoded, $method=-1)
 Return a file on output using a low memory. More...
 
 showValueWithClipboardCPButton ($valuetocopy, $showonlyonhover=1, $texttoshow='')
 Create a button to copy $valuetocopy in the clipboard (for copy and paste feature). More...
 
 jsonOrUnserialize ($stringtodecode)
 Decode an encode string. More...
 
 forgeSQLFromUniversalSearchCriteria ($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
 forgeSQLFromUniversalSearchCriteria More...
 
 dolForgeExplodeAnd ($sqlfilters)
 Explode an universal search string with AND parts. More...
 
 dolCheckFilters ($sqlfilters, &$error='', &$parenthesislevel=0)
 Return if a $sqlfilters parameter has a valid balance of parenthesis. More...
 
 dolForgeDummyCriteriaCallback ($matches)
 Function to forge a SQL criteria from a Dolibarr filter syntax string. More...
 
 dolForgeCriteriaCallback ($matches)
 Function to forge a SQL criteria from a Dolibarr filter syntax string. More...
 
 getTimelineIcon ($actionstatic, &$histo, $key)
 Get timeline icon. More...
 
 getActionCommEcmList ($object)
 getActionCommEcmList More...
 
 show_actions_messaging ($conf, $langs, $db, $filterobj, $objcon=null, $noprint=0, $actioncode='', $donetodo='done', $filters=array(), $sortfield='a.datep, a.id', $sortorder='DESC')
 Show html area with actions in messaging format. More...
 
 GETPOSTDATE ($prefix, $hourTime='', $gm='auto')
 Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and optionally hour, minute, second) fields to return a timestamp. More...
 
 buildParamDate ($prefix, $timestamp=null, $hourTime='', $gm='auto')
 Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and optionally hour, minute, second) fields to return a a portion of URL reproducing the values from the current HTTP request. More...
 
 recordNotFound ($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
 Displays an error page when a record is not found. More...
 

Variables

const MODULE_MAPPING array( 'adherent' => 'member', 'member_type' => 'adherent_type', 'banque' => 'bank', 'contrat' => 'contract', 'entrepot' => 'stock', 'projet' => 'project', 'categorie' => 'category', 'commande' => 'order', 'expedition' => 'shipping', 'facture' => 'invoice', 'fichinter' => 'intervention', 'ficheinter' => 'intervention', 'propale' => 'propal', 'socpeople' => 'contact', 'fournisseur' => 'supplier', 'actioncomm' => 'agenda', 'product_price' => 'productprice', 'product_fournisseur_price' => 'productsupplierprice', )
 This mapping defines the conversion to the current internal names from the alternative allowed names (including effectively deprecated and future new names (not yet used as internal names). More...
 

Detailed Description

A set of functions for Dolibarr This file contains all frequently used functions.

Definition in file functions.lib.php.

Function Documentation

◆ addSummaryTableLine()

addSummaryTableLine (   $tableColumnCount,
  $num,
  $nbofloop = 0,
  $total = 0,
  $noneWord = "None",
  $extraRightColumn = false 
)

Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")

Parameters
integer$tableColumnCountThe complete count columns of the table
integer$numThe count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
integer$nbofloop(optional) The maximum count of rows thaht the table show (when it is zero (0) no summary line will show, expect "$noneWord" when $num === 0)
integer$total(optional) The total value thaht is shown after when the table has minimum of one entire
string$noneWord(optional) The word that is shown when the table has no entries ($num === 0)
boolean$extraRightColumn(optional) Add a additional column after the summary word and total number
Returns
void

Definition at line 13006 of file functions.lib.php.

◆ ajax_autoselect()

ajax_autoselect (   $htmlname,
  $addlink = '',
  $textonlink = 'Link' 
)

Make content of an input box selected when we click into input field.

Parameters
string$htmlnameId of html object ('#idvalue' or '.classvalue')
string$addlinkAdd a 'link to' after
string$textonlinkText to show on link or 'image'
Returns
string

Definition at line 11412 of file functions.lib.php.

◆ ascii_check()

ascii_check (   $str)

Check if a string is in ASCII.

Parameters
string$strString to check
Returns
boolean True if string is ASCII, False if not (byte value > 0x7F)

Definition at line 9997 of file functions.lib.php.

◆ buildParamDate()

buildParamDate (   $prefix,
  $timestamp = null,
  $hourTime = '',
  $gm = 'auto' 
)

Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and optionally hour, minute, second) fields to return a a portion of URL reproducing the values from the current HTTP request.

Parameters
string$prefixPrefix used to build the date selector (for instance using Form::selectDate)
?int$timestamp If null, the timestamp will be created from request data
string$hourTimeIf timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
string$gmIf timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
Returns
string Portion of URL with query parameters for the specified date

Definition at line 14329 of file functions.lib.php.

◆ checkVal()

checkVal (   $out = '',
  $check = 'alphanohtml',
  $filter = null,
  $options = null 
)

Return a sanitized or empty value after checking value against a rule.

Deprecated:
Parameters
string | array$outValue to check/clear.
string$checkType of check/sanitizing
int$filterFilter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
mixed$optionsOptions to pass to filter_var when $check is set to 'custom'
Returns
string|array Value sanitized (string or array). It may be '' if format check fails.

Definition at line 1099 of file functions.lib.php.

◆ colorIsLight()

colorIsLight (   $stringcolor)

Return true if the color is light.

Parameters
string$stringcolorString with hex (FFFFFF) or comma RGB ('255,255,255')
Returns
int<-1,1> -1 : Error with argument passed |0 : color is dark | 1 : color is light

Definition at line 11831 of file functions.lib.php.

◆ complete_head_from_modules()

complete_head_from_modules (   $conf,
  $langs,
  $object,
$head,
$h,
  $type,
  $mode = 'add',
  $filterorigmodule = '' 
)

Complete or removed entries into a head array (used to build tabs).

For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab']. Or by change using hook completeTabsHead

Parameters
Conf$confObject conf
Translate$langsObject langs
object | null$objectObject object
array<array<int,string>>$head List of head tabs (updated by this function)
int$hNew position to fill (updated by this function)
string$typeValue for object where objectvalue can be 'thirdparty' to add a tab in third party view 'intervention' to add a tab in intervention view 'supplier_order' to add a tab in purchase order view 'supplier_invoice' to add a tab in purchase invoice view 'invoice' to add a tab in sales invoice view 'order' to add a tab in sales order view 'contract' to add a table in contract view 'product' to add a tab in product view 'propal' to add a tab in propal view 'user' to add a tab in user view 'group' to add a tab in group view 'member' to add a tab in foundation member view 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member) 'ecm' to add a tab for another ecm view 'stock' to add a tab for warehouse view
string$mode'add' to complete head, 'remove' to remove entries
string$filterorigmoduleFilter on module origin: 'external' will show only external modules. 'core' only core modules. No filter (default) will add both.
Returns
void

Definition at line 10664 of file functions.lib.php.

◆ complete_substitutions_array()

complete_substitutions_array ( $substitutionarray,
  $outputlangs,
  $object = null,
  $parameters = null,
  $callfunc = "completesubstitutionarray" 
)

Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.

In this case, method completesubstitutionarray provided by module is called.

Parameters
array<string,string>$substitutionarray Array substitution old value => new value value
Translate$outputlangsOutput language
CommonObject$objectSource object
mixed$parametersAdd more parameters (useful to pass product lines)
string$callfuncWhat is the name of the custom function that will be called? (default: completesubstitutionarray)
Returns
void
See also
make_substitutions()

Definition at line 9451 of file functions.lib.php.

◆ currentToken()

currentToken ( )

Return the value of token currently saved into session with name 'token'.

For ajax call, you must use this token as a parameter of the call into the js calling script (the called ajax php page must also set constant NOTOKENRENEWAL).

Since
Dolibarr v10.0.7
Returns
string

Definition at line 12902 of file functions.lib.php.

◆ dol_bc()

dol_bc (   $var,
  $moreclass = '' 
)

Return string to add class property on html element with pair/impair.

Parameters
boolean$varfalse or true
string$moreclassMore class to add
Returns
string String to add class onto HTML element

Definition at line 3036 of file functions.lib.php.

◆ dol_buildpath()

dol_buildpath (   $path,
  $type = 0,
  $returnemptyifnotfound = 0 
)

Return path of url or filesystem.

Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.

Parameters
string$pathRelative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
int$type0=Used for a Filesystem path, 1=Used for an URL path (output relative), 2=Used for an URL path (output full path using same host that current url), 3=Used for an URL path (output full path using host defined into $dolibarr_main_url_root of conf file)
int$returnemptyifnotfound0:If $type==0 and if file was not found into alternate dir, return default path into main dir (no test on it) 1:If $type==0 and if file was not found into alternate dir, return empty string 2:If $type==0 and if file was not found into alternate dir, test into main dir, return default path if found, empty string if not found
Returns
string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)

Definition at line 1332 of file functions.lib.php.

Referenced by DolibarrCollector\getAssets().

◆ dol_clone()

dol_clone (   $object,
  $native = 0 
)

Create a clone of instance of object (new instance with same value for each properties) With native = 0: Property that are references are different memory area in the new object (full isolation clone).

This means $this->object of new object may not be valid (except this->db that is voluntarly kept). With native = 1: Use PHP clone. Property that are reference are same pointer. This means $this->db of new object is still valid but point to same this->db than original object. With native = 2: Property that are reference are different memory area in the new object (full isolation clone). Only scalar and array values are cloned. This means method are not availables and $this->db of new object is not valid.

@template T of object

Parameters
T$objectObject to clone
int$native0=Full isolation method, 1=Native PHP method, 2=Full isolation method keeping only scalar and array properties (recommended)
Returns
T Clone object
See also
https://php.net/manual/language.oop5.cloning.php @phan-suppress PhanTypeExpectedObjectPropAccess

Definition at line 1469 of file functions.lib.php.

Referenced by Fichinter\setDraft(), and Fichinter\setRefClient().

◆ dol_concatdesc()

dol_concatdesc (   $text1,
  $text2,
  $forxml = false,
  $invert = false 
)

Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator) text1 html + text2 html => text1 + '
' + text2 text1 html + text2 txt => text1 + '
' + dol_nl2br(text2) text1 txt + text2 html => dol_nl2br(text1) + '
' + text2 text1 txt + text2 txt => text1 + '
' + text2.

Parameters
string$text1Text 1
string$text2Text 2
bool$forxmltrue=Use
instead of
if we have to add a br tag
bool$invertinvert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
Returns
string Text 1 + new line + Text2
See also
dol_textishtml()

Definition at line 8541 of file functions.lib.php.

◆ dol_escape_htmltag()

dol_escape_htmltag (   $stringtoescape,
  $keepb = 0,
  $keepn = 0,
  $noescapetags = '',
  $escapeonlyhtmltags = 0,
  $cleanalsojavascript = 0 
)

Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input fields.

When we need to output strings on pages, we should use:

  • dolPrintHTML... that is dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1)), 1, 1) for notes or descriptions into textarea, add 'common' if into a html content
  • dolPrintPassword that is abelhtmlspecialchars( , ENT_COMPAT, 'UTF-8') for passwords.
Parameters
string$stringtoescapeString to escape
int$keepb1=Replace b tags with escaped value (except if in $noescapetags), 0=Remove them completely
int$keepn1=Preserve \r
strings, 0=Replace them with escaped value, -1=Remove them. Set to 1 when escaping for a <textarea>.
string$noescapetags'' or 'common' or list of tags to not escape.
int$escapeonlyhtmltags1=Escape only html tags, not the special chars like accents.
int$cleanalsojavascriptClean also javascript. @TODO switch this option to 1 by default.
Returns
string Escaped string
See also
dol_string_nohtmltag(), dol_string_onlythesehtmltags(), dol_string_nospecial(), dol_string_unaccent(), dol_htmlentitiesbr()

Definition at line 1919 of file functions.lib.php.

◆ dol_escape_js()

dol_escape_js (   $stringtoescape,
  $mode = 0,
  $noescapebackslashn = 0 
)

Returns text escaped for inclusion into javascript code.

Parameters
string$stringtoescapeString to escape
int<0,3>$mode 0=Escape also ' and " into ', 1=Escape ' but not " for usage into 'string', 2=Escape " but not ' for usage into "string", 3=Escape ' and " with \
int$noescapebackslashn0=Escape also
. 1=Do not escape
.
Returns
string Escaped string. Both ' and " are escaped into ' if they are escaped.

Definition at line 1762 of file functions.lib.php.

◆ dol_escape_json()

dol_escape_json (   $stringtoescape)

Returns text escaped for inclusion into javascript code.

Parameters
string$stringtoescapeString to escape
Returns
string Escaped string for JSON content.

Definition at line 1795 of file functions.lib.php.

◆ dol_escape_php()

dol_escape_php (   $stringtoescape,
  $stringforquotes = 2 
)

Returns text escaped for inclusion into a php string, build with double quotes " or '.

Parameters
string$stringtoescapeString to escape
int<1,2>$stringforquotes 2=String for doublequotes, 1=String for simple quotes
Returns
string Escaped string for PHP content.

Definition at line 1807 of file functions.lib.php.

◆ dol_escape_xml()

dol_escape_xml (   $stringtoescape)

Returns text escaped for inclusion into a XML string.

Parameters
string$stringtoescapeString to escape
Returns
string Escaped string for XML content.

Definition at line 1834 of file functions.lib.php.

◆ dol_eval()

dol_eval (   $s,
  $returnvalue = 1,
  $hideerrors = 1,
  $onlysimplestring = '1' 
)

Replace eval function to add more security.

This function is called by verifCond() or trans() and transnoentitiesnoconv().

Parameters
string$sString to evaluate
int<0,1>$returnvalue 0=No return (deprecated, used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
int<0,1>$hideerrors 1=Hide errors
string$onlysimplestring'0' (deprecated, do not use it anymore)=Accept all chars, '1' (most common use)=Accept only simple string with char 'a-z0-9\s^$_+-.*>&|=!?():"\',/@';', '2' (used for example for the compute property of extrafields)=Accept also '[]'
Returns
void|string Nothing or return result of eval (even if type can be int, it is safer to assume string and find all potential typing issues as abs(dol_eval(...)).
See also
verifCond() @phan-suppress PhanPluginUnsafeEval

Definition at line 10161 of file functions.lib.php.

◆ dol_fiche_end()

dol_fiche_end (   $notab = 0)

Show tab footer of a card.

Parameters
int<-1,1>$notab -1 or 0=Add tab footer, 1=no tab footer
Returns
void
Deprecated:
Use print dol_get_fiche_end() instead

Definition at line 2618 of file functions.lib.php.

◆ dol_fiche_head()

dol_fiche_head (   $links = array(),
  $active = '0',
  $title = '',
  $notab = 0,
  $picto = '',
  $pictoisfullpath = 0,
  $morehtmlright = '',
  $morecss = '',
  $limittoshow = 0,
  $moretabssuffix = '' 
)

Show tab header of a card.

Parameters
array<string,array<int<0,5>,string>>$links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
string$activeActive tab name (document', 'info', 'ldap', ....)
string$titleTitle
int$notab-1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no sepaaration under tab (to start a tab just after), -3=Add tab header but no footer separation
string$pictoAdd a picto on tab title
int$pictoisfullpathIf 1, image path is a full path. If you set this to 1, you can use url returned by dol_buildpath('/mymodyle/img/myimg.png',1) for $picto.
string$morehtmlrightAdd more html content on right of tabs title
string$morecssMore Css
int$limittoshowLimit number of tabs to show. Use 0 to use automatic default value.
string$moretabssuffixA suffix to use when you have several dol_get_fiche_head() in same page
Returns
void
Deprecated:
Use print dol_get_fiche_head() instead

Definition at line 2406 of file functions.lib.php.

◆ dol_format_address()

dol_format_address (   $object,
  $withcountry = 0,
  $sep = "\n",
  $outputlangs = null,
  $mode = 0,
  $extralangcode = '' 
)

Return a formatted address (part address/zip/town/state) according to country rules.

See https://en.wikipedia.org/wiki/Address

Parameters
Object$objectA company or contact object
int$withcountry1=Add country into address string
string$sepSeparator to use to separate info when building string
?Translate$outputlangs Object lang that contains language for text translation.
int$mode0=Standard output, 1=Remove address
string$extralangcodeUser extralanguage $langcode as values for address, town
Returns
string Formatted string
See also
dol_print_address()

Definition at line 3059 of file functions.lib.php.

◆ dol_get_fiche_end()

dol_get_fiche_end (   $notab = 0)

Return tab footer of a card.

Parameters
int<-1,1>$notab -1 or 0=Add tab footer, 1=no tab footer
Returns
string

Definition at line 2629 of file functions.lib.php.

◆ dol_get_fiche_head()

dol_get_fiche_head (   $links = array(),
  $active = '',
  $title = '',
  $notab = 0,
  $picto = '',
  $pictoisfullpath = 0,
  $morehtmlright = '',
  $morecss = '',
  $limittoshow = 0,
  $moretabssuffix = '',
  $dragdropfile = 0 
)

Show tabs of a record.

Parameters
array<int,array<int<0,5>,string>>$links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
string$activeActive tab name
string$titleTitle
int$notab-1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no separation under tab (to start a tab just after), -3=-2+'noborderbottom'
string$pictoAdd a picto on tab title
int$pictoisfullpathIf 1, image path is a full path. If you set this to 1, you can use url returned by dol_buildpath('/mymodyle/img/myimg.png',1) for $picto.
string$morehtmlrightAdd more html content on right of tabs title
string$morecssMore CSS on the link
int$limittoshowLimit number of tabs to show. Use 0 to use automatic default value.
string$moretabssuffixA suffix to use when you have several dol_get_fiche_head() in same page
int$dragdropfile0 (default) or 1. 1 enable a drop zone for file to be upload, 0 disable it
Returns
string

Definition at line 2427 of file functions.lib.php.

◆ dol_get_object_properties()

dol_get_object_properties (   $obj,
  $properties = [] 
)

Get properties for an object - including magic properties when requested.

Only returns properties that exist

Parameters
object$objObject to get properties from
string[]$propertiesOptional list of properties to get. When empty, only gets public properties.
Returns
array<string,mixed> Hash for retrieved values (key=name)

Definition at line 1430 of file functions.lib.php.

◆ dol_getdate()

dol_getdate (   $timestamp,
  $fast = false,
  $forcetimezone = '' 
)

Return an array with locale date info.

WARNING: This function use PHP server timezone by default to return locale information. Be aware to add the third parameter to "UTC" if you need to work on UTC.

Parameters
int$timestampTimestamp
boolean$fastFast mode. deprecated.
string$forcetimezone'' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
Returns
array{}|array{seconds:int<0,59>,minutes:int<0,59>,hours:int<0,23>,mday:int<1,31>,wday:int<0,6>,mon:int<1,12>,year:int<0,9999>,yday:int<0,366>,0:int} Array of information 'seconds' => $secs, 'minutes' => $min, 'hours' => $hour, 'mday' => $day, 'wday' => $dow, 0=sunday, 6=saturday 'mon' => $month, 'year' => $year, 'yday' => floor($secsInYear/$_day_power) '0' => original timestamp
See also
dol_print_date(), dol_stringtotime(), dol_mktime()

Definition at line 3436 of file functions.lib.php.

◆ dol_getIdFromCode()

dol_getIdFromCode (   $db,
  $key,
  $tablename,
  $fieldkey = 'code',
  $fieldid = 'id',
  $entityfilter = 0,
  $filters = '' 
)

Return an id or code from a code or id.

Store also Code-Id into a cache to speed up next request on same table and key.

Parameters
DoliDB$dbDatabase handler
string$keyCode or Id to get Id or Code
string$tablenameTable name without prefix
string$fieldkeyField to search the key into
string$fieldidField to get
int$entityfilterFilter by entity
string$filtersFilters to add. WARNING: string must be escaped for SQL and not coming from user input.
Returns
int<-1,max>|string ID of code if OK, 0 if key empty, -1 if KO
See also
$langs->getLabelFromKey

Definition at line 10055 of file functions.lib.php.

◆ dol_getmypid()

dol_getmypid ( )

Return getmypid() or random PID when function is disabled Some web hosts disable this php function for security reasons and sometimes we can't redeclare function.

Returns
int

Definition at line 11088 of file functions.lib.php.

◆ dol_html_entity_decode()

dol_html_entity_decode (   $a,
  $b,
  $c = 'UTF-8',
  $keepsomeentities = 0 
)

Replace html_entity_decode functions to manage errors.

Parameters
string$aOperand a
string$bOperand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
string$cOperand c
int$keepsomeentitiesEntities but &, <, >, " are not converted.
Returns
string String decoded

Definition at line 8338 of file functions.lib.php.

◆ dol_htmlcleanlastbr()

dol_htmlcleanlastbr (   $stringtodecode)

This function remove all ending
and br at end.

Parameters
string$stringtodecodeString to decode
Returns
string String decoded

Definition at line 8322 of file functions.lib.php.

◆ dol_htmlentities()

dol_htmlentities (   $string,
  $flags = ENT_QUOTES | ENT_SUBSTITUTE,
  $encoding = 'UTF-8',
  $double_encode = false 
)

Replace htmlentities functions.

Goal of this function is to be sure to have default values of htmlentities that match what we need.

Parameters
string$stringThe input string to encode
int$flagsFlags (see PHP doc above)
string$encodingEncoding page code
bool$double_encodeWhen double_encode is turned off, PHP will not encode existing html entities
Returns
string $ret Encoded string
See also
dol_htmlentitiesbr()

Definition at line 8362 of file functions.lib.php.

◆ dol_htmlentitiesbr()

dol_htmlentitiesbr (   $stringtoencode,
  $nl2brmode = 0,
  $pagecodefrom = 'UTF-8',
  $removelasteolbr = 1 
)

This function is called to encode a string into a HTML string but differs from htmlentities because a detection is done before to see if text is already HTML or not.

Also, all entities but &,<,>," are converted. This permits to encode special chars to entities with no double encoding for already encoded HTML strings. This function also remove last EOL or BR if $removelasteolbr=1 (default). For PDF usage, you can show text by 2 ways:

  • writeHTMLCell -> param must be encoded into HTML.
  • MultiCell -> param must not be encoded into HTML. Because writeHTMLCell convert also
    into
    , if function is used to build PDF, nl2brmode must be 1. Note: When we output string on pages, we should use
  • dolPrintHTML... that is dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1), 1, 1) for notes or descriptions,
  • dolPrintPassword that is abelhtmlspecialchars( , ENT_COMPAT, 'UTF-8') for passwords.
Parameters
string$stringtoencodeString to encode
int$nl2brmode0=Adding br before
, 1=Replacing
by br (for use with FPDF writeHTMLCell function for example)
string$pagecodefromPagecode stringtoencode is encoded
int$removelasteolbr1=Remove last br or lasts
(default), 0=Do nothing
Returns
string String encoded
See also
dol_escape_htmltag(), dolGetFirstLineOfText(), dol_string_onlythesehtmltags()

Definition at line 8273 of file functions.lib.php.

◆ dol_htmlentitiesbr_decode()

dol_htmlentitiesbr_decode (   $stringtodecode,
  $pagecodeto = 'UTF-8' 
)

This function is called to decode a HTML string (it decodes entities and br tags)

Parameters
string$stringtodecodeString to decode
string$pagecodetoPage code for result
Returns
string String decoded

Definition at line 8306 of file functions.lib.php.

Referenced by AdherentType\getMailOnExclude(), AdherentType\getMailOnResiliate(), AdherentType\getMailOnSubscription(), and AdherentType\getMailOnValid().

◆ dol_htmloutput_errors()

dol_htmloutput_errors (   $mesgstring = '',
  $mesgarray = array(),
  $keepembedded = 0 
)

Print formatted error messages to output (Used to show messages on html output).

Parameters
string$mesgstringError message
string[]$mesgarrayError messages array
int<0,1>$keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
Returns
void
See also
dol_print_error()
dol_htmloutput_mesg()

Definition at line 9867 of file functions.lib.php.

◆ dol_htmloutput_events()

dol_htmloutput_events (   $disabledoutputofmessages = 0)

Print formatted messages to output (Used to show messages on html output).

Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is no need to call it explicitly.

Parameters
int$disabledoutputofmessagesClear all messages stored into session without displaying them
Returns
void
See also
dol_htmloutput_mesg()

Definition at line 9672 of file functions.lib.php.

◆ dol_htmloutput_mesg()

dol_htmloutput_mesg (   $mesgstring = '',
  $mesgarray = array(),
  $style = 'ok',
  $keepembedded = 0 
)

Print formatted messages to output (Used to show messages on html output).

Parameters
string$mesgstringMessage string or message key
string[]$mesgarrayArray of message strings or message keys
string$styleWhich style to use ('ok', 'warning', 'error')
int$keepembeddedSet to 1 if message must be kept embedded into its html place (this disable jnotify)
Returns
void
See also
dol_print_error()
dol_htmloutput_errors()
setEventMessages()

Definition at line 9799 of file functions.lib.php.

◆ dol_htmlwithnojs()

dol_htmlwithnojs (   $stringtoencode,
  $nouseofiframesandbox = 0,
  $check = 'restricthtml' 
)

Sanitize a HTML to remove js, dangerous content and external link.

This function is used by dolPrintHTML... function for example.

Parameters
string$stringtoencodeString to encode
int$nouseofiframesandbox0=Default, 1=Allow use of option MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS for html sanitizing (not yet working)
string$check'restricthtmlnolink' or 'restricthtml' or 'restricthtmlallowclass' or 'restricthtmlallowunvalid'
Returns
string HTML sanitized
Parameters
string[]$m
Returns
string

Definition at line 8091 of file functions.lib.php.

◆ dol_include_once()

if (!function_exists( 'dol_getprefix')) dol_include_once (   $relpath,
  $classname = '' 
)

Make an include_once using default root and alternate root if it fails.

To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile') To link to a module file from a module file, use include './mymodulefile'; To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)

Parameters
string$relpathRelative path to file (Ie: mydir/myfile, ../myfile, ...)
string$classnameClass name (deprecated)
Returns
bool True if load is a success, False if it fails

Definition at line 1303 of file functions.lib.php.

◆ dol_mimetype()

dol_mimetype (   $file,
  $default = 'application/octet-stream',
  $mode = 0 
)

Return MIME type of a file from its name with extension.

Parameters
string$fileFilename we looking for MIME type
string$defaultDefault mime type if extension not found in known list
int<0,4>$mode 0=Return full mime, 1=otherwise short mime string, 2=image for mime type, 3=source language, 4=css of font fa
Returns
string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
See also
dolIsAllowedForPreview(), image_format_supported() from images.lib.php

Definition at line 11470 of file functions.lib.php.

◆ dol_mkdir()

dol_mkdir (   $dir,
  $dataroot = '',
  $newmask = '' 
)

Creation of a directory (this can create recursive subdir)

Parameters
string$dirDirectory to create (Separator must be '/'. Example: '/mydir/mysubdir')
string$datarootData root directory (To avoid having the data root in the loop. Using this will also lost the warning, on first dir, saying PHP has no permission when open_basedir is used)
string$newmaskMask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
Returns
int Return integer < 0 if KO, 0 = already exists, > 0 if OK

Definition at line 7628 of file functions.lib.php.

◆ dol_mktime()

dol_mktime (   $hour,
  $minute,
  $second,
  $month,
  $day,
  $year,
  $gm = 'auto',
  $check = 1 
)

Return a timestamp date built from detailed information (by default a local PHP server timestamp) Replace function mktime not available under Windows if year < 1970 PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows.

Parameters
int$hourHour (can be -1 for undefined)
int$minuteMinute (can be -1 for undefined)
int$secondSecond (can be -1 for undefined)
int$monthMonth (1 to 12)
int$dayDay (1 to 31)
int$yearYear
mixed$gmTrue or 1 or 'gmt'=Input information are GMT values False or 0 or 'tzserver' = local to server TZ 'auto' 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented. 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user into a GMT date. 'tz,TimeZone' = use specified timezone
int$check0=No check on parameters (Can use day 32, etc...)
Returns
int|string Date as a timestamp, '' if error
See also
dol_print_date(), dol_stringtotime(), dol_getdate()

Definition at line 3483 of file functions.lib.php.

◆ dol_nboflines()

dol_nboflines (   $s,
  $maxchar = 0 
)

Return nb of lines of a clear text.

Parameters
string$sString to check
int$maxcharNot yet used
Returns
int Number of lines
See also
dol_nboflines_bis(), dolGetFirstLineOfText()

Definition at line 8410 of file functions.lib.php.

◆ dol_nboflines_bis()

dol_nboflines_bis (   $text,
  $maxlinesize = 0,
  $charset = 'UTF-8' 
)

Return nb of lines of a formatted text with
and
(WARNING: string must not have mixed
and br separators)

Parameters
string$textText
int$maxlinesizeLinewidth in character count (default = 0 == nolimit)
string$charsetGive the charset used to encode the $text variable in memory.
Returns
int Number of lines
See also
dol_nboflines(), dolGetFirstLineOfText()

Definition at line 8431 of file functions.lib.php.

◆ dol_nl2br()

dol_nl2br (   $stringtoencode,
  $nl2brmode = 0,
  $forxml = false 
)

Replace CRLF in string with a HTML BR tag.

WARNING: The content after operation contains some HTML tags (the
) so be sure to also have encoded the special chars of stringtoencode into HTML before with dol_htmlentitiesbr().

Parameters
string$stringtoencodeString to encode
int$nl2brmode0=Adding br before
, 1=Replacing
by br
bool$forxmlfalse=Use
, true=Use
Returns
string String encoded
See also
dol_htmlentitiesbr(), dol_nboflines(), dolGetFirstLineOfText()

Definition at line 8068 of file functions.lib.php.

◆ dol_now()

dol_now (   $mode = 'auto')

Return date for now.

In most cases, we use this function without parameters (that means GMT time).

Parameters
string$mode'auto' => for backward compatibility (avoid this), 'gmt' => we return GMT timestamp, 'tzserver' => we add the PHP server timezone 'tzref' => we add the company timezone. Not implemented. 'tzuser' or 'tzuserrel' => we add the user timezone
Returns
int $date Timestamp

Definition at line 3571 of file functions.lib.php.

Referenced by BonPrelevement\__construct(), Dolresource\create(), dolSessionGC(), dolSessionWrite(), getServerTimeZoneInt(), BOM\initAsSpecimen(), PaymentVarious\initAsSpecimen(), Localtax\initAsSpecimen(), ChargeSociales\initAsSpecimen(), PaymentSocialContribution\initAsSpecimen(), PaymentVAT\initAsSpecimen(), Tva\initAsSpecimen(), PaymentDonation\initAsSpecimen(), PaymentExpenseReport\initAsSpecimen(), Productbatch\initAsSpecimen(), ProductStockEntrepot\initAsSpecimen(), PaymentSalary\initAsSpecimen(), Salary\initAsSpecimen(), InterfaceLogevents\initEventData(), Dolresource\updateElementResource(), and FichinterRec\updateNbGenDone().

◆ dol_osencode()

dol_osencode (   $str)

Return a string encoded into OS filesystem encoding.

This function is used to define value to pass to filesystem PHP functions.

Parameters
string$strString to encode (UTF-8)
Returns
string Encoded string (UTF-8, ISO-8859-1)

Definition at line 10021 of file functions.lib.php.

Referenced by CMailFile\_encode_file(), dol_filemtime(), dol_fileperm(), dol_filesize(), dol_is_file(), dol_is_link(), and dol_is_writable().

◆ dol_print_address()

dol_print_address (   $address,
  $htmlid,
  $element,
  $id,
  $noprint = 0,
  $charfornl = '' 
)

Format address string.

Parameters
string$addressAddress string, already formatted with dol_format_address()
int$htmlidHtml ID (for example 'gmap')
int$element'thirdparty'|'contact'|'member'|'user'|'other'
int$idId of object
int$noprintNo output. Result is the function return
string$charfornlChar to use instead of nl2br. '' means we use a standad nl2br.
Returns
string|void Nothing if noprint is 0, formatted address if noprint is 1
See also
dol_format_address()

Definition at line 4422 of file functions.lib.php.

◆ dol_print_date()

dol_print_date (   $time,
  $format = '',
  $tzoutput = 'auto',
  $outputlangs = null,
  $encodetooutput = false 
)

Output date in a string format according to outputlangs (or langs if not defined).

Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset

Parameters
int | string$timeGM Timestamps date
string$formatOutput date format (tag of strftime function) "%d %b %Y", "%d/%m/%Y %H:%M", "%d/%m/%Y %H:%M:%S", "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
string | bool$tzoutputtrue or 'gmt' => string is for Greenwich location false or 'tzserver' => output string is for local PHP server TZ usage 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel' 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
Translate$outputlangsObject lang that contains language for text translation.
boolean$encodetooutputfalse=no convert into output pagecode
Returns
string Formatted date or '' if time is null
See also
dol_mktime(), dol_stringtotime(), dol_getdate(), selectDate()

Definition at line 3182 of file functions.lib.php.

Referenced by BonPrelevement\EnregEmetteur(), getServerTimeZoneInt(), numero_semaine(), and ExpenseReport\offsetAlreadyGiven().

◆ dol_print_email()

dol_print_email (   $email,
  $cid = 0,
  $socid = 0,
  $addlink = 0,
  $max = 64,
  $showinvalid = 1,
  $withpicto = 0 
)

Show EMail link formatted for HTML output.

Parameters
string$emailEMail to show (only email, without 'Name of recipient' before)
int$cidId of contact if known
int$socidId of third party if known
int$addlink0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
int$maxMax number of characters to show
int$showinvalid1=Show warning if syntax email is wrong
int | string$withpictoShow picto
Returns
string HTML Link

Definition at line 3696 of file functions.lib.php.

◆ dol_print_error()

dol_print_error (   $db = null,
  $error = '',
  $errors = null 
)

Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.

This function must be called when a blocking technical error is encountered. However, one must try to call it only within php pages, classes must return their error through their property "error".

Parameters
DoliDB | null$dbDatabase handler
string | string[]$errorString or array of errors strings to show
string[] | null$errorsArray of errors
Returns
void
See also
dol_htmloutput_errors()

Definition at line 5766 of file functions.lib.php.

Referenced by Product\getChildsArbo(), Product\getFather(), FichinterRec\setAutoValidate(), FactureFournisseurRec\setAutoValidate(), FichinterRec\setFrequencyAndUnit(), FactureFournisseurRec\setGeneratePdf(), FichinterRec\setMaxPeriod(), FactureFournisseurRec\setMaxPeriod(), FichinterRec\setNextDate(), and FichinterRec\updateNbGenDone().

◆ dol_print_error_email()

dol_print_error_email (   $prefixcode,
  $errormessage = '',
  $errormessages = array(),
  $morecss = 'error',
  $email = '' 
)

Show a public email and error code to contact if technical error.

Parameters
string$prefixcodePrefix of public error code
string$errormessageComplete error message
string[]$errormessagesArray of error messages
string$morecssMore css
string$emailEmail
Returns
void

Definition at line 5915 of file functions.lib.php.

◆ dol_print_ip()

dol_print_ip (   $ip,
  $mode = 0 
)

Return an IP formatted to be shown on screen.

Parameters
string$ipIP
int$mode0=return IP + country/flag, 1=return only country/flag, 2=return only IP
Returns
string Formatted IP, with country if GeoIP module is enabled

Definition at line 4288 of file functions.lib.php.

◆ dol_print_phone()

dol_print_phone (   $phone,
  $countrycode = '',
  $cid = 0,
  $socid = 0,
  $addlink = '',
  $separ = "&nbsp;",
  $withpicto = '',
  $titlealt = '',
  $adddivfloat = 0 
)

Format phone numbers according to country.

Parameters
string$phonePhone number to format
string$countrycodeCountry code to use for formatting
int$cidId of contact if known
int$socidId of third party if known
string$addlink''=no link to create action, 'AC_TEL'=add link to clicktodial (if module enabled) and add link to create event (if conf->global->AGENDA_ADDACTIONFORPHONE set), 'tel'=Force "tel:..." link
string$separSeparation between numbers for a better visibility example : xx.xx.xx.xx.xx. You can also use 'hidenum' to hide the number, keep only the picto.
string$withpictoShow picto ('fax', 'phone', 'mobile')
string$titlealtText to show on alt
int$adddivfloatAdd div float around phone.
Returns
string Formatted phone number

Definition at line 3956 of file functions.lib.php.

◆ dol_print_profids()

dol_print_profids (   $profID,
  $profIDtype,
  $countrycode = '',
  $addcpButton = 1 
)

Format professional IDs according to their country.

Parameters
string$profIDValue of profID to format
string$profIDtypeType of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
string$countrycodeCountry code to use for formatting
int<0,2>$addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
Returns
string Formatted profID

Definition at line 3900 of file functions.lib.php.

◆ dol_print_size()

dol_print_size (   $size,
  $shortvalue = 0,
  $shortunit = 0 
)

Return string with formatted size.

Parameters
int$sizeSize to print
int$shortvalueTell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
int$shortunitUse short label of size unit (for example 'b' instead of 'bytes')
Returns
string Link

Definition at line 3610 of file functions.lib.php.

◆ dol_print_socialnetworks()

dol_print_socialnetworks (   $value,
  $cid,
  $socid,
  $type,
  $dictsocialnetworks = array() 
)

Show social network link.

Parameters
string$valueSocial network ID to show (only skype, without 'Name of recipient' before)
int$cidId of contact if known
int$socidId of third party if known
string$type'skype','facebook',...
array<string,array{rowid:int,label:string,url:string,icon:string,active:int}>$dictsocialnetworks List of socialnetworks available
Returns
string HTML Link

Definition at line 3813 of file functions.lib.php.

◆ dol_print_url()

dol_print_url (   $url,
  $target = '_blank',
  $max = 32,
  $withpicto = 0,
  $morecss = '' 
)

Show Url link.

Parameters
string$urlUrl to show
string$targetTarget for link
int$maxMax number of characters to show
int$withpictoWith picto
string$morecssMore CSS
Returns
string HTML Link

Definition at line 3649 of file functions.lib.php.

◆ dol_sanitizeEmail()

dol_sanitizeEmail (   $stringtoclean)

Clean a string to use it as an Email.

Parameters
string$stringtocleanString to clean. Example 'abc@m.nosp@m.ycom.nosp@m.pany..nosp@m.com <My name>'
Returns
string Escaped string.

Definition at line 1621 of file functions.lib.php.

◆ dol_sanitizeFileName()

dol_sanitizeFileName (   $str,
  $newstr = '_',
  $unaccent = 1 
)

Clean a string to use it as a file name.

Replace also '–' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).

Parameters
string$strString to clean
string$newstrString to replace bad chars with.
int$unaccent1=Remove also accent (default), 0 do not remove them
Returns
string String cleaned (a-zA-Z_)
See also
dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()

Definition at line 1537 of file functions.lib.php.

Referenced by Product\check().

◆ dol_sanitizePathName()

dol_sanitizePathName (   $str,
  $newstr = '_',
  $unaccent = 1 
)

Clean a string to use it as a path name.

Similar to dol_sanitizeFileName but accept / and \ chars. Replace also '–' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).

Parameters
string$strString to clean
string$newstrString to replace bad chars with
int$unaccent1=Remove also accent (default), 0 do not remove them
Returns
string String cleaned (a-zA-Z_)
See also
dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()

Definition at line 1564 of file functions.lib.php.

◆ dol_sanitizeUrl()

dol_sanitizeUrl (   $stringtoclean,
  $type = 1 
)

Clean a string to use it as an URL (into a href or src attribute)

Parameters
string$stringtocleanString to clean
int$type0=Accept all Url, 1=Clean external Url (keep only relative Url)
Returns
string Escaped string.

Definition at line 1585 of file functions.lib.php.

◆ dol_set_focus()

dol_set_focus (   $selector)

Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)

Parameters
string$selectorSelector ('#id' or 'input[name="ref"]') to use to find the HTML input field that must get the autofocus. You must use a CSS selector, so unique id preceding with the '#' char.
Returns
void

Definition at line 11074 of file functions.lib.php.

◆ dol_shutdown()

dol_shutdown ( )

Function called at end of web php process.

Returns
void

Definition at line 624 of file functions.lib.php.

◆ dol_size()

dol_size (   $size,
  $type = '' 
)

Optimize a size for some browsers (phone, smarphone, ...)

Parameters
int$sizeSize we want
string$typeType of optimizing: '' = function used to define a size for truncation 'width' = function is used to define a width
Returns
int New size after optimizing

Definition at line 1512 of file functions.lib.php.

◆ dol_sort_array()

dol_sort_array ( $array,
  $index,
  $order = 'asc',
  $natsort = 0,
  $case_sensitive = 0,
  $keepindex = 0 
)

Advanced sort array by the value of a given key, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well).

Parameters
array<string|int,mixed>$array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
string$indexKey in array to use for sorting criteria
string$orderSort order ('asc' or 'desc')
int<0,1>$natsort If values are strings (I said value not type): 0=Use alphabetical order, 1=use "natural" sort (natsort) If values are numeric (I said value not type): 0=Use numeric order (even if type is string) so use a "natural" sort, 1=use "natural" sort too (same than 0), -1=Force alphabetical order
int<0,1>$case_sensitive 1=sort is case sensitive, 0=not case sensitive
int<0,1>$keepindex If 0 and index key of array to sort is a numeric, then index will be rewritten. If 1 or index key is not numeric, key for index is kept after sorting.
Returns
array<string|int,mixed> Return the sorted array (the source array is not modified !)

Definition at line 9885 of file functions.lib.php.

◆ dol_strftime()

dol_strftime (   $fmt,
  $ts = false,
  $is_gmt = false 
)

Format a string.

Parameters
string$fmtFormat of strftime function (http://php.net/manual/fr/function.strftime.php)
int | false$tsTimestamp (If is_gmt is true, timestamp is already includes timezone and daylight saving offset, if is_gmt is false, timestamp is a GMT timestamp and we must compensate with server PHP TZ)
bool$is_gmtSee comment of timestamp parameter
Returns
string A formatted string
See also
dol_stringtotime()

Definition at line 3152 of file functions.lib.php.

◆ dol_string_is_good_iso()

dol_string_is_good_iso (   $s,
  $clean = 0 
)

Check if a string is a correct iso string If not, it will not be considered as HTML encoded even if it is by FPDF.

Example, if string contains euro symbol that has ascii code 128

Parameters
string$sString to check
int$cleanClean if it is not an ISO. Warning, if file is utf8, you will get a bad formatted file.
Returns
int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
Deprecated:
Duplicate of ascii_check()
See also
ascii_check()

Definition at line 8378 of file functions.lib.php.

◆ dol_string_neverthesehtmltags()

dol_string_neverthesehtmltags (   $stringtoclean,
  $disallowed_tags = array('textarea'),
  $cleanalsosomestyles = 0 
)

Clean a string from some undesirable HTML tags.

Note: You should use instead dol_string_onlythesehtmltags() that is more secured if you can.

Parameters
string$stringtocleanString to clean
array$disallowed_tagsArray of tags not allowed
int$cleanalsosomestylesClean also some tags
Returns
string String cleaned
See also
dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()

Definition at line 7968 of file functions.lib.php.

◆ dol_string_nohtmltag()

dol_string_nohtmltag (   $stringtoclean,
  $removelinefeed = 1,
  $pagecodeto = 'UTF-8',
  $strip_tags = 0,
  $removedoublespaces = 1 
)

Clean a string from all HTML tags and entities.

This function differs from strip_tags because:


  • are replaced with
    if removelinefeed=0 or 1
  • if entities are found, they are decoded BEFORE the strip
  • you can decide to convert line feed into a space
Parameters
string$stringtocleanString to clean
integer$removelinefeed1=Replace all new lines by 1 space, 0=Only ending new lines are removed others are replaced with
, 2=The ending new line is removed but others are kept with the same number of
than the nb of
when there is both "...<br>\n..."
string$pagecodetoEncoding of input/output string
integer$strip_tags0=Use internal strip, 1=Use strip_tags() php function (bugged when text contains a < char that is not for a html tag or when tags is not closed like '<img onload=aaa')
integer$removedoublespacesReplace double space into one space
Returns
string String cleaned
See also
dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()

Definition at line 7739 of file functions.lib.php.

Referenced by ExportExcel2007\excel_clean(), and AccountancyExport\toAnsi().

◆ dol_string_nospecial()

dol_string_nospecial (   $str,
  $newstr = '_',
  $badcharstoreplace = '',
  $badcharstoremove = '',
  $keepspaces = 0 
)

Clean a string from all punctuation characters to use it as a ref or login.

This is a more complete function than dol_sanitizeFileName().

Parameters
string$strString to clean
string$newstrString to replace forbidden chars with
array | string$badcharstoreplaceArray of forbidden characters to replace. Use '' to keep default list.
array | string$badcharstoremoveArray of forbidden characters to remove. Use '' to keep default list.
int$keepspaces1=Do not treat space as a special char to replace or remove
Returns
string Cleaned string
See also
dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()

Definition at line 1711 of file functions.lib.php.

◆ dol_string_nounprintableascii()

dol_string_nounprintableascii (   $str,
  $removetabcrlf = 1 
)

Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F).

It can also removes also Tab-CR-LF. UTF8 chars remains. This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars. Note, for information: UTF8 on 1 byte are: \x00-\7F 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf

Parameters
string$strString to clean
int$removetabcrlfRemove also CR-LF
Returns
string Cleaned string
See also
dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()

Definition at line 1745 of file functions.lib.php.

◆ dol_string_onlythesehtmlattributes()

dol_string_onlythesehtmlattributes (   $stringtoclean,
  $allowed_attributes = null 
)

Clean a string from some undesirable HTML tags.

Note: Complementary to dol_string_onlythesehtmltags(). This method is used for example by dol_htmlwithnojs() when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.

Parameters
string$stringtocleanString to clean
string[]$allowed_attributesArray of tags not allowed
Returns
string String cleaned
See also
dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags() @phan-suppress PhanUndeclaredProperty

Definition at line 7883 of file functions.lib.php.

◆ dol_string_onlythesehtmltags()

dol_string_onlythesehtmltags (   $stringtoclean,
  $cleanalsosomestyles = 1,
  $removeclassattribute = 1,
  $cleanalsojavascript = 0,
  $allowiframe = 0,
  $allowed_tags = array(),
  $allowlink = 0 
)

Clean a string to keep only desirable HTML tags.

WARNING: This also clean HTML comments (because they can be used to obfuscate tag name).

Parameters
string$stringtocleanString to clean
int$cleanalsosomestylesRemove absolute/fixed positioning from inline styles
int$removeclassattribute1=Remove the class attribute from tags
int$cleanalsojavascriptRemove also occurrence of 'javascript:'.
int$allowiframeAllow iframe tags.
string[]$allowed_tagsList of allowed tags to replace the default list
int$allowlinkAllow "link" tags.
Returns
string String cleaned
See also
dol_htmlwithnojs() dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()

Definition at line 7813 of file functions.lib.php.

◆ dol_string_unaccent()

dol_string_unaccent (   $str)

Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.

Parameters
string$strString to clean
Returns
string Cleaned string
See also
dol_sanitizeFilename(), dol_string_nospecial()

Definition at line 1639 of file functions.lib.php.

◆ dol_strlen()

dol_strlen (   $string,
  $stringencoding = 'UTF-8' 
)

Make a strlen call.

Works even if mbstring module not enabled

Parameters
string$stringString to calculate length
string$stringencodingEncoding of string
Returns
int Length of string

Definition at line 4584 of file functions.lib.php.

Referenced by binhex(), dol_ch_controle_bvrb(), isValidLuhn(), and Ldap\littleEndian().

◆ dol_strtolower()

dol_strtolower (   $string,
  $encoding = "UTF-8" 
)

Convert a string to lower.

Never use strtolower because it does not works with UTF8 strings.

Parameters
string$stringString to encode
string$encodingCharacter set encoding
Returns
string String converted

Definition at line 2003 of file functions.lib.php.

◆ dol_strtoupper()

dol_strtoupper (   $string,
  $encoding = "UTF-8" 
)

Convert a string to upper.

Never use strtolower because it does not works with UTF8 strings.

Parameters
string$stringString to encode
string$encodingCharacter set encoding
Returns
string String converted
See also
dol_ucfirst(), dol_ucwords()

Definition at line 2020 of file functions.lib.php.

◆ dol_substr()

dol_substr (   $string,
  $start,
  $length = null,
  $stringencoding = '',
  $trunconbytes = 0 
)

Make a substring.

Works even if mbstring module is not enabled for better compatibility.

Parameters
string$stringString to scan
int$startStart position (0 for first char)
int | null$lengthLength (in nb of characters or nb of bytes depending on trunconbytes param)
string$stringencodingPage code used for input string encoding
int$trunconbytes1=Length is max of bytes instead of max of characters
Returns
string substring

Definition at line 4607 of file functions.lib.php.

Referenced by AccountancyExport\toAnsi().

◆ dol_syslog()

dol_syslog (   $message,
  $level = LOG_INFO,
  $ident = 0,
  $suffixinfilename = '',
  $restricttologhandler = '',
  $logcontext = null 
)

Write log message into outputs.

Possible outputs can be: SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve this, use logging to files instead of syslog (see setup of module). Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails. Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set) This function works only if syslog module is enabled. This must not use any call to other function calling dol_syslog (avoid infinite loop).

Parameters
string$messageLine to log. ''=Show nothing
int$levelLog level On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=6, LOG_DEBUG=6 if define_syslog_variables ou PHP 5.3+, 7 if dolibarr On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
int$ident1=Increase ident of 1 (after log), -1=Decrease ident of 1 (before log)
string$suffixinfilenameWhen output is a file, append this suffix into default log filename. Example '_stripe', '_mail'
string$restricttologhandlerForce output of log only to this log handler
array | null$logcontextIf defined, an array with extra information (can be used by some log handlers)
Returns
void @phan-suppress PhanPluginUnknownArrayFunctionParamType $logcontext is not defined in detail

Definition at line 2085 of file functions.lib.php.

Referenced by MailmanSpip\add_to_spip(), Propal\availability(), Commande\availability(), Lettering\bookkeepingLetteringAll(), Categorie\buildPathFromId(), MouvementStock\calculateBalanceForProductBefore(), check_user_password_forceuser(), Commande\classifyBilled(), Commande\classifyUnBilled(), MailingTargets\clear_target(), User\clearrights(), Product\clone_associations(), DoliDBMysqli\close(), DoliDBPgsql\close(), DoliDBSqlite3\close(), MailmanSpip\connectSpip(), Categorie\containsObject(), Categorie\countNbOfCategories(), ProductStockEntrepot\create(), Fournisseur\CreateCategory(), BookKeeping\createFromClone(), EcmFiles\createFromClone(), Productlot\createFromClone(), ProductStockEntrepot\createFromClone(), DoliDBPgsql\DDLCreateUser(), MailmanSpip\del_to_spip(), Ldap\delete(), SupplierInvoiceLine\delete(), Deplacement\delete(), Link\delete(), Menubase\delete(), Establishment\delete(), Categorie\delete(), ActionComm\delete(), PaymentSocialContribution\delete(), PaymentVAT\delete(), PaymentExpenseReport\delete(), Productbatch\delete(), PaymentSalary\delete(), EcmFiles\delete(), KnowledgeRecord\delete(), CurrencyRate\delete(), Productlot\delete(), ProductStockEntrepot\delete(), Cronjob\delete(), CompanyBankAccount\delete(), UserBankAccount\delete(), Mailing\delete_targets(), ExpeditionLineBatch\deleteFromShipment(), Lettering\deleteLettering(), FactureFournisseur\deleteLine(), FichinterLigne\deleteLine(), AdherentType\delMultiLangs(), Product\delMultiLangs(), Propal\demand_reason(), Commande\demand_reason(), dol_json_decode(), dol_json_encode(), dolCheckOnFileName(), Adherent\exclude(), PrestaShopWebservice\executeRequest(), Localtax\fetch(), Fiscalyear\fetch(), Delivery\fetch(), EcmDirectory\fetch(), PaymentExpenseReport\fetch(), Establishment\fetch(), Import\fetch(), Loan\fetch(), CurrencyRate\fetch(), Productbatch\fetch(), PriceGlobalVariable\fetch(), PriceGlobalVariableUpdater\fetch(), MouvementStock\fetch(), PaymentTerm\fetch(), CGenericDic\fetch(), Ctyperesource\fetch(), MultiCurrency\fetch(), ProductStockEntrepot\fetch(), Opensurveysondage\fetch(), Account\fetch(), Deplacement\fetch(), ChargeSociales\fetch(), Tva\fetch(), CommandeFournisseur\fetch(), Holiday\fetch(), ReceptionLineBatch\fetch(), Task\fetch(), Contrat\fetch(), Reception\fetch(), Project\fetch(), Commande\fetch(), Website\fetch(), Partnership\fetch(), PaymentVarious\fetch(), Menubase\fetch(), Salary\fetch(), FactureFournisseur\fetch(), FactureLigneRec\fetch(), FichinterLigne\fetch(), FactureFournisseurLigneRec\fetch(), Cronjob\fetch(), Dolresource\fetch(), CommandeFournisseur\fetch_lines(), Facture\fetch_lines(), Propal\fetch_lines(), FactureRec\fetch_lines(), Fichinter\fetch_lines(), FactureFournisseurRec\fetch_lines(), FactureFournisseur\fetch_lines(), Dolresource\fetchElementResource(), ExpeditionLineBatch\fetchFromStock(), Task\fetchTimeSpent(), PriceExpression\find_title(), User\get_children(), Account\get_url(), ExpenseReportIk\getAllRanges(), Product\getChildsArbo(), Holiday\getConfCP(), SocieteAccount\getCustomerAccount(), Lettering\getDocTypeAndFkDocFromBankLines(), Dolresource\getElementResources(), SupplierProposal\getLinesArray(), ExpenseReportIk\getMaxRangeNumber(), Commande\getNbOfShipments(), Don\getRemainToPay(), CommonObject\getTotalDiscount(), Adherent\info(), ActionComm\info(), PaymentVarious\info(), Deplacement\info(), Paiement\info(), ChargeSociales\info(), Tva\info(), Fiscalyear\info(), Don\info(), PaymentExpenseReport\info(), Establishment\info(), Loan\info(), Entrepot\info(), Salary\info(), Cronjob\info(), Categorie\initAsSpecimen(), ExpenseReportLine\insert(), FichinterLigne\insert(), OrderLine\insert(), CommonObject\line_max(), CommonObject\line_order(), PriceExpression\list_price_expression(), PriceGlobalVariable\listGlobalVariables(), ModeleImports\listOfAvailableImportFormat(), PriceGlobalVariableUpdater\listPendingUpdaters(), PriceGlobalVariableUpdater\listUpdaters(), Categorie\load_motherof(), Ticket\loadCacheMsgsTicket(), User\loadParentOf(), CommandeFournisseur\loadReceptions(), ExpenseReport\offsetAlreadyGiven(), Zapier\post(), DoliDBMysqli\query(), DoliDBPgsql\query(), Paiement\reject(), Project\remove_element(), Propal\reopen(), Societe\replaceThirdparty(), Mailing\reset_targets_status(), Ldap\search(), DoliDBMysqli\select_db(), DoliDBSqlite3\select_db(), Propal\set_availability(), Facture\set_canceled(), Commande\set_date(), Propal\set_demand_reason(), Propal\set_echeance(), CommandeFournisseur\set_id_projet(), RemiseCheque\set_number(), ChargeSociales\set_paid(), Salary\set_paid(), Facture\set_paid(), FactureFournisseur\set_paid(), Facture\set_ref_client(), Propal\set_ref_client(), Commande\set_ref_client(), Commande\set_remise(), Facture\set_remise(), Commande\set_reopen(), Loan\set_started(), Facture\set_unpaid(), ChargeSociales\set_unpaid(), FactureFournisseur\set_unpaid(), CompanyPaymentMode\setAsDefault(), CompanyBankAccount\setAsDefault(), FichinterRec\setAutoValidate(), FactureFournisseurRec\setAutoValidate(), FactureRec\setAutoValidate(), Facture\setCanceled(), FactureFournisseur\setCanceled(), Delivery\setDeliveryDate(), Expedition\setDeliveryDate(), Reception\setDeliveryDate(), Propal\setDeliveryDate(), Commande\setDeliveryDate(), CommandeFournisseur\setDeliveryDate(), Commande\setDiscount(), Facture\setDiscount(), Fichinter\setDraft(), Propal\setDraft(), CommonObject\setExtraParameters(), Facture\setFinal(), FichinterRec\setFrequencyAndUnit(), FactureFournisseurRec\setFrequencyAndUnit(), FactureRec\setFrequencyAndUnit(), FactureFournisseurRec\setGeneratePdf(), FactureRec\setGeneratePdf(), FichinterRec\setMaxPeriod(), FactureFournisseurRec\setMaxPeriod(), FactureRec\setMaxPeriod(), FichinterRec\setNextDate(), FactureFournisseurRec\setNextDate(), FactureRec\setNextDate(), Societe\setParent(), Ticket\setProgression(), Fichinter\setRefClient(), Societe\setThirdpartyType(), Facture\setUnpaid(), FactureFournisseur\setUnpaid(), Conf\setValues(), FactureFournisseur\setVATReverseCharge(), DiscountAbsolute\unlink_invoice(), FichinterLigne\update(), ExpeditionLigne\update(), Productbatch\update(), CurrencyRate\update(), Productlot\update(), ProductStockEntrepot\update(), User\update_clicktodial(), Paiement\update_date(), Adherent\update_end_date(), Paiement\update_fk_bank(), PaymentSocialContribution\update_fk_bank(), PaymentVAT\update_fk_bank(), PaymentDonation\update_fk_bank(), PaymentExpenseReport\update_fk_bank(), PaymentLoan\update_fk_bank(), PaymentSalary\update_fk_bank(), Paiement\update_num(), CommonObject\update_ref_ext(), Contrat\update_statut(), FactureLigne\update_total(), FichinterRec\updateNbGenDone(), Paiement\validate(), and Holiday\verifNbUsers().

◆ dol_textishtml()

dol_textishtml (   $msg,
  $option = 0 
)

Return if a text is a html content.

Parameters
string$msgContent to check
int$option0=Full detection, 1=Fast check
Returns
boolean true/false
See also
dol_concatdesc()

Definition at line 8474 of file functions.lib.php.

◆ dol_trunc()

dol_trunc (   $string,
  $size = 40,
  $trunc = 'right',
  $stringencoding = 'UTF-8',
  $nodot = 0,
  $display = 0 
)

Truncate a string to a particular length adding '…' if string larger than length.

If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'. MAIN_DISABLE_TRUNC=1 can disable all truncings

Parameters
string$stringString to truncate
int$sizeMax string size visible (excluding …). 0 for no limit. WARNING: Final string size can have 3 more chars (if we added …, or if size was max+1 so it does not worse to replace with ...)
string$truncWhere to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
string$stringencodingTell what is source string encoding
int$nodotTruncation do not add … after truncation. So it's an exact truncation.
int$displayTrunc is used to display data and can be changed for small screen. TODO Remove this param (must be dealt with CSS)
Returns
string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.

Definition at line 4646 of file functions.lib.php.

Referenced by WebsitePage\create(), AccountancyExport\trunc(), and WebsitePage\update().

◆ dol_ucfirst()

dol_ucfirst (   $string,
  $encoding = "UTF-8" 
)

Convert first character of the first word of a string to upper.

Never use ucfirst because it does not works with UTF8 strings.

Parameters
string$stringString to encode
string$encodingCharacter set encodign
Returns
string String converted
See also
dol_strtoupper(), dol_ucwords()

Definition at line 2037 of file functions.lib.php.

◆ dol_ucwords()

dol_ucwords (   $string,
  $encoding = "UTF-8" 
)

Convert first character of all the words of a string to upper.

Parameters
string$stringString to encode
string$encodingCharacter set encodign
Returns
string String converted
See also
dol_strtoupper(), dol_ucfirst()

Definition at line 2054 of file functions.lib.php.

◆ dol_user_country()

dol_user_country ( )

Return country code for current user.

If software is used inside a local network, detection may fails (we need a public ip)

Returns
string Country code (fr, es, it, us, ...)

Definition at line 4391 of file functions.lib.php.

◆ dol_validElement()

dol_validElement (   $element)

Return if var element is ok.

Parameters
string$elementVariable to check
Returns
boolean Return true of variable is not empty
See also
getElementProperties()

Definition at line 10346 of file functions.lib.php.

◆ dolButtonToOpenExportDialog()

dolButtonToOpenExportDialog (   $name,
  $label,
  $buttonstring,
  $exportSiteName,
  $overwriteGitUrl,
  $website 
)

Create a dialog with two buttons for export and overwrite of a website.

Parameters
string$nameUnique identifier for the dialog
string$labelTitle of the dialog
string$buttonstringText for the button that opens the dialog
string$exportSiteNameName of the "submit" input for site export
string$overwriteGitUrlURL for the link that triggers the overwrite action in GIT
Website$websiteWebsite object
Returns
string HTML and JavaScript code for the button and the dialog

Definition at line 2212 of file functions.lib.php.

◆ dolButtonToOpenUrlInDialogPopup()

dolButtonToOpenUrlInDialogPopup (   $name,
  $label,
  $buttonstring,
  $url,
  $disabled = '',
  $morecss = 'classlink button bordertransp',
  $jsonopen = '',
  $backtopagejsfields = '',
  $accesskey = '' 
)

Return HTML code to output a button to open a dialog popup box.

Such buttons must be included inside a HTML form.

Parameters
string$nameA name for the html component
string$labelLabel shown in Popup title top bar
string$buttonstringbutton string (HTML text we can click on)
string$urlRelative Url to open. For example '/project/card.php'
string$disabledDisabled text
string$morecssMore CSS
string$jsonopenSome JS code to execute on click/open of popup
string$backtopagejsfieldsThe back to page must be managed using javascript instead of a redirect. Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
string$accesskeyA key to use shortcut
Returns
string HTML component with button

Definition at line 2306 of file functions.lib.php.

◆ dolCheckFilters()

dolCheckFilters (   $sqlfilters,
$error = '',
$parenthesislevel = 0 
)

Return if a $sqlfilters parameter has a valid balance of parenthesis.

Parameters
string$sqlfiltersUniversal SQL filter string. Must have been trimmed before.
string$errorReturned error message
int$parenthesislevelReturned level of global parenthesis that we can remove/simplify, 0 if error or we can't simplify.
Returns
boolean True if valid, False if not valid ($error returned parameter is filled with the reason in such a case)
See also
forgeSQLFromUniversalSearchCriteria()

Definition at line 13282 of file functions.lib.php.

◆ dolChmod()

dolChmod (   $filepath,
  $newmask = '' 
)

Change mod of a file.

Parameters
string$filepathFull file path
string$newmaskForce new mask. For example '0644'
Returns
void

Definition at line 7700 of file functions.lib.php.

Referenced by Website\checkPreviousState(), and Website\replaceLineUsingNum().

◆ dolExplodeIntoArray()

dolExplodeIntoArray (   $string,
  $delimiter = ';',
  $kv = '=' 
)

Split a string with 2 keys into key array.

For example: "A=1;B=2;C=2" is exploded into array('A'=>'1','B'=>'2','C'=>'3')

Parameters
?string$string String to explode
string$delimiterDelimiter between each couple of data. Example: ';' or '[
;]+' or '(
\r|\r|
|;)'
string$kvDelimiter between key and value
Returns
array<string,string> Array of data exploded

Definition at line 11035 of file functions.lib.php.

◆ dolForgeCriteriaCallback()

dolForgeCriteriaCallback (   $matches)

Function to forge a SQL criteria from a Dolibarr filter syntax string.

This method is called by forgeSQLFromUniversalSearchCriteria()

Parameters
string[]$matchesArray of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.date_creation:<:'2016-01-01 12:30:00'" or "t.nature:is:NULL"
Returns
string Forged criteria. Example: "t.field LIKE 'abc%'"

Definition at line 13364 of file functions.lib.php.

Referenced by DolibarrApi\_forge_criteria_callback().

◆ dolForgeDummyCriteriaCallback()

dolForgeDummyCriteriaCallback (   $matches)

Function to forge a SQL criteria from a Dolibarr filter syntax string.

This method is called by forgeSQLFromUniversalSearchCriteria()

Parameters
string[]$matchesArray of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
Returns
string Forged criteria. Example: "" or "()"

Definition at line 13342 of file functions.lib.php.

◆ dolForgeExplodeAnd()

dolForgeExplodeAnd (   $sqlfilters)

Explode an universal search string with AND parts.

This is used to output the search criteria in an UFS (Universal Filter Syntax) input component.

Parameters
string$sqlfiltersUniversal SQL filter string. Must have been trimmed before.
Returns
string[] Array of AND

Definition at line 13215 of file functions.lib.php.

◆ dolGetBadge()

dolGetBadge (   $label,
  $html = '',
  $type = 'primary',
  $mode = '',
  $url = '',
  $params = array() 
)

Function dolGetBadge.

Parameters
string$labellabel of badge no html : use in alt attribute for accessibility
string$htmloptional : label of badge with html
string$typetype of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
''|'pill'|'dot'$mode Default '' , 'pill', 'dot'
string$urlthe url for link
array<string,mixed>$params Various params for future : recommended rather than adding more function arguments. array('attr'=>array('title'=>'abc'))
Returns
string Html badge

Definition at line 11924 of file functions.lib.php.

◆ dolGetButtonAction()

dolGetButtonAction (   $label,
  $text = '',
  $actionType = 'default',
  $url = '',
  $id = '',
  $userRight = 1,
  $params = array() 
)

Function dolGetButtonAction.

Parameters
string$labelLabel or tooltip of button if $text is provided. Also used as tooltip in title attribute. Can be escaped HTML content or full simple text.
string$textOptional : short label on button. Can be escaped HTML content or full simple text.
string$actionType'default', 'danger', 'email', 'clone', 'cancel', 'delete', ...
string|array<int,array{lang:string,enabled:bool,perm:bool,label:string,url:string}>$url Url for link or array of subbutton description
                                                                                                         Example when an array is used: $arrayforbutaction = array(
                                                                                                         10 => array('lang'=>'propal', 'enabled'=>isModEnabled("propal"), 'perm'=>$user->hasRight('propal', 'creer'), 'label' => 'AddProp', 'url'=>'/comm/propal/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
                                                                                                         20 => array('lang'=>'orders', 'enabled'=>isModEnabled("order"), 'perm'=>$user->hasRight('commande', 'creer'), 'label' => 'CreateOrder', 'url'=>'/commande/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
                                                                                                         30 => array('lang'=>'bills', 'enabled'=>isModEnabled("invoice"), 'perm'=>$user->hasRight('facture', 'creer'), 'label' => 'CreateBill', 'url'=>'/compta/facture/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
                                                                                                         );
string$idAttribute id of action button. Example 'action-delete'. This can be used for full ajax confirm if this code is reused into the ->formconfirm() method.
int | boolean$userRightUser action right // phpcs:disable
array<string,mixed>$params = [ // Various params for future : recommended rather than adding more function arguments 'attr' => [ // to add or override button attributes 'xxxxx' => '', // your xxxxx attribute you want 'class' => 'reposition', // to add more css class to the button class attribute 'classOverride' => '' // to replace class attribute of the button ], 'confirm' => [ 'url' => 'http://', // Override Url to go when user click on action btn, if empty default url is $url.?confirm=yes, for no js compatibility use $url for fallback confirm. 'title' => '', // Override title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key 'action-btn-label' => '', // Override label of action button, if empty default label use "Confirm" lang key 'cancel-btn-label' => '', // Override label of cancel button, if empty default label use "CloseDialog" lang key 'content' => '', // Override text of content, if empty default content use "ConfirmBtnCommonContent" lang key 'modal' => true, // true|false to display dialog as a modal (with dark background) 'isDropDrown' => false, // true|false to display dialog as a dropdown (with dark background) ], ] // phpcs:enable
Returns
string html button

Definition at line 12113 of file functions.lib.php.

◆ dolGetButtonTitle()

dolGetButtonTitle (   $label,
  $helpText = '',
  $iconClass = 'fa fa-file',
  $url = '',
  $id = '',
  $status = 1,
  $params = array() 
)

Function dolGetButtonTitle : this kind of buttons are used in title in list.

Parameters
string$labellabel of button
string$helpTextoptional : content for help tooltip
string$iconClassclass for icon element (Example: 'fa fa-file')
string$urlthe url for link
string$idattribute id of button
int<-2,2>$status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use param $helpText as tooltip help
array<string,mixed>$params various params for future : recommended rather than adding more function arguments
Returns
string html button

Definition at line 12337 of file functions.lib.php.

◆ dolGetButtonTitleSeparator()

dolGetButtonTitleSeparator (   $moreClass = "")

Add space between dolGetButtonTitle.

Parameters
string$moreClassmore css class label
Returns
string html of title separator

Definition at line 12302 of file functions.lib.php.

◆ dolGetCountryCodeFromIp()

dolGetCountryCodeFromIp (   $ip)

Return a country code from IP.

Empty string if not found.

Parameters
string$ipIP
Returns
string Country code ('us', 'fr', ...)

Definition at line 4365 of file functions.lib.php.

◆ dolGetFirstLastname()

dolGetFirstLastname (   $firstname,
  $lastname,
  $nameorder = -1 
)

Return firstname and lastname in correct order.

Parameters
string$firstnameFirstname
string$lastnameLastname
int$nameorder-1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
Returns
string Firstname + lastname or Lastname + firstname

Definition at line 9552 of file functions.lib.php.

◆ dolGetFirstLetters()

dolGetFirstLetters (   $s,
  $nbofchar = 1 
)

Return first letters of a strings.

Example with nbofchar=1: 'ghi' will return 'g' but 'abc def' will return 'ad' Example with nbofchar=2: 'ghi' will return 'gh' but 'abc def' will return 'abde'

Parameters
string$sString to truncate
int$nbofcharNb of characters to keep
Returns
string Return first chars.

Definition at line 4565 of file functions.lib.php.

◆ dolGetFirstLineOfText()

dolGetFirstLineOfText (   $text,
  $nboflines = 1,
  $charset = 'UTF-8' 
)

Return first line of text.

Cut will depends if content is HTML or not.

Parameters
string$textInput text
int$nboflinesNb of lines to get (default is 1 = first line only)
string$charsetCharset of $text string (UTF-8 by default)
Returns
string Output text
See also
dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()

Definition at line 7993 of file functions.lib.php.

◆ dolGetStatus()

dolGetStatus (   $statusLabel = '',
  $statusLabelShort = '',
  $html = '',
  $statusType = 'status0',
  $displayMode = 0,
  $url = '',
  $params = array() 
)

Output the badge of a status.

Parameters
string$statusLabelLabel of badge no html : use in alt attribute for accessibility
string$statusLabelShortShort label of badge no html
string$htmlOptional : label of badge with html
string$statusTypestatus0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
int<0,6>$displayMode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
string$urlThe url for link
array<string,mixed>$params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
Returns
string Html status string

Definition at line 11993 of file functions.lib.php.

◆ dolIsAllowedForPreview()

dolIsAllowedForPreview (   $file)

Return if a file is qualified for preview.

Parameters
string$fileFilename we looking for information
Returns
int<0,1> 1 If allowed, 0 otherwise
See also
dol_mimetype(), image_format_supported() from images.lib.php

Definition at line 11437 of file functions.lib.php.

◆ dolPrintHTML()

dolPrintHTML (   $s,
  $allowiframe = 0 
)

Return a string (that can be on several lines) ready to be output on a HTML page.

To output a text inside an attribute, you can use dolPrintHTMLForAttribute() or dolPrintHTMLForTextArea() inside a textarea

Parameters
string$sString to print
int$allowiframeAllow iframe tags
Returns
string String ready for HTML output (sanitized and escape)
See also
dolPrintHTMLForAttribute(), dolPrintHTMLFortextArea()

Definition at line 1860 of file functions.lib.php.

◆ dolPrintHTMLForAttribute()

dolPrintHTMLForAttribute (   $s)

Return a string ready to be output on an HTML attribute (alt, title, data-html, ...)

Parameters
string$sString to print
Returns
string String ready for HTML output
See also
dolPrintHTML(), dolPrintHTMLFortextArea()

Definition at line 1872 of file functions.lib.php.

◆ dolPrintHTMLForTextArea()

dolPrintHTMLForTextArea (   $s,
  $allowiframe = 0 
)

Return a string ready to be output on input textarea.

Parameters
string$sString to print
int$allowiframeAllow iframe tags
Returns
string String ready for HTML output into a textarea
See also
dolPrintHTML(), dolPrintHTMLForAttribute()

Definition at line 1887 of file functions.lib.php.

◆ dolPrintLabel()

dolPrintLabel (   $s)

Return a string label (so on 1 line only and that should not contains any HTML) ready to be output on HTML page To use text that is not HTML content inside an attribute, use can simply only dol_escape_htmltag().

In doubt, use dolPrintHTMLForAttribute().

Parameters
string$sString to print
Returns
string String ready for HTML output

Definition at line 1846 of file functions.lib.php.

◆ dolPrintPassword()

dolPrintPassword (   $s)

Return a string ready to be output on an HTML attribute (alt, title, ...)

Parameters
string$sString to print
Returns
string String ready for HTML output

Definition at line 1898 of file functions.lib.php.

◆ fetchObjectByElement()

fetchObjectByElement (   $element_id,
  $element_type,
  $element_ref = '',
  $useCache = 0,
  $maxCacheByType = 10 
)

Fetch an object from its id and element_type Inclusion of classes is automatic.

Parameters
int$element_idElement id (Use this or element_ref but not both. If id and ref are empty, object with no fetch is returned)
string$element_typeElement type ('module' or 'myobject@mymodule' or 'mymodule_myobject')
string$element_refElement ref (Use this or element_id but not both. If id and ref are empty, object with no fetch is returned)
int<0,2>$useCache If you want to store object in cache or get it from cache 0 => no use cache , 1 use cache, 2 force reload cache
int$maxCacheByTypeNumber of object in cache for this element type
Returns
int<-1,0>|object object || 0 || <0 if error
See also
getElementProperties()

Definition at line 12797 of file functions.lib.php.

◆ fieldLabel()

fieldLabel (   $langkey,
  $fieldkey,
  $fieldrequired = 0 
)

Show a string with the label tag dedicated to the HTML edit field.

Parameters
string$langkeyTranslation key
string$fieldkeyKey of the html select field the text refers to
int$fieldrequired1=Field is mandatory
Returns
string
Deprecated:
Form::editfieldkey

Definition at line 3013 of file functions.lib.php.

◆ finishSimpleTable()

finishSimpleTable (   $addLineBreak = false)

Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)

Parameters
bool$addLineBreak(optional) Add a extra line break after the complete table (<br>)
Returns
void
See also
startSimpleTable()

Definition at line 12985 of file functions.lib.php.

◆ forgeSQLFromUniversalSearchCriteria()

forgeSQLFromUniversalSearchCriteria (   $filter,
$errorstr = '',
  $noand = 0,
  $nopar = 0,
  $noerror = 0 
)

forgeSQLFromUniversalSearchCriteria

Parameters
string$filterString with universal search string. Must be '(aaa:bbb:ccc) OR (ddd:eeee:fff) ...' with aaa is a field name (with alias or not) and bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'. ccc must not contains ( or ) Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a')'
string$errorstrError message string
int<0,1>$noand 1=Do not add the AND before the condition string.
int<0,1>$nopar 1=Do not add the parenthesis around the final condition string.
int<0,1>$noerror 1=If search criteria is not valid, does not return an error string but invalidate the SQL
Returns
string Return forged SQL string
See also
dolSqlDateFilter()
natural_search()

Definition at line 13159 of file functions.lib.php.

◆ get_date_range()

get_date_range (   $date_start,
  $date_end,
  $format = '',
  $outputlangs = null,
  $withparenthesis = 1 
)

Format output for start and end date.

Parameters
int$date_startStart date
int$date_endEnd date
string$formatOutput date format ('day', 'dayhour', ...)
Translate$outputlangsOutput language
integer$withparenthesis1=Add parenthesis, 0=no parenthesis
Returns
string String

Definition at line 9521 of file functions.lib.php.

◆ get_default_localtax()

get_default_localtax (   $thirdparty_seller,
  $thirdparty_buyer,
  $local,
  $idprod = 0 
)

Function that return localtax of a product line (according to seller, buyer and product vat rate) If the seller is not subject to VAT, then default VAT=0.

Rule/Test ends. If (seller country == buyer country) default VAT=sold product VAT. Rule/Test ends. Else, default VAT=0. Rule/Test ends

Parameters
Societe$thirdparty_sellerThird party seller
Societe$thirdparty_buyerThird party buyer
int$localLocaltax to process (1 or 2)
int$idprodId product
Returns
int localtax, -1 if it can not be determined
See also
get_default_tva(), get_default_npr()

Definition at line 7461 of file functions.lib.php.

◆ get_default_npr()

get_default_npr ( Societe  $thirdparty_seller,
Societe  $thirdparty_buyer,
  $idprod = 0,
  $idprodfournprice = 0 
)

Function that returns whether VAT must be recoverable collected VAT (e.g.

: VAT NPR in France)

Parameters
Societe$thirdparty_sellerThirdparty seller
Societe$thirdparty_buyerThirdparty buyer
int$idprodId product
int$idprodfournpriceId supplier price for product
Returns
float 0 or 1
See also
get_default_tva(), get_default_localtax()

Definition at line 7425 of file functions.lib.php.

◆ get_default_tva()

get_default_tva ( Societe  $thirdparty_seller,
Societe  $thirdparty_buyer,
  $idprod = 0,
  $idprodfournprice = 0 
)

Function that return vat rate of a product line (according to seller, buyer and product vat rate) VATRULE 1: If seller does not use VAT, default VAT is 0.

End of rule. VATRULE 2: If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule. VATRULE 3: If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule. VATRULE 4: If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule VATRULE 5: If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule VATRULE 6: Otherwise the VAT proposed by default=0. End of rule.

Parameters
Societe$thirdparty_sellerObject Seller company
Societe$thirdparty_buyerObject Buyer company
int$idprodId product
int$idprodfournpriceId product_fournisseur_price (for supplier order/invoice)
Returns
float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
See also
get_default_localtax(), get_default_npr()

Definition at line 7309 of file functions.lib.php.

◆ get_exdir()

get_exdir (   $num,
  $level,
  $alpha,
  $withoutslash,
  $object,
  $modulepart = '' 
)

Return a path to have a the directory according to object where files are stored.

New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/' or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined. Example out with new usage: $object is invoice -> 'INYYMM-ABCD' Example out with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"

Parameters
string | int$numId of object (deprecated, $object will be used in future)
int$levelLevel of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
int$alpha0=Keep number only to forge path, 1=Use alpha part after the - (By default, use 0). (deprecated, global option will be used in future)
int$withoutslash0=With slash at end (except if '/', we return ''), 1=without slash at end
?CommonObject$object Object to use to get ref to forge the path.
string$modulepartType of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
Returns
string Dir to use ending. Example '' or '1/' or '1/2/'
See also
getMultidirOutput()

Definition at line 7576 of file functions.lib.php.

◆ get_htmloutput_errors()

get_htmloutput_errors (   $mesgstring = '',
  $mesgarray = array(),
  $keepembedded = 0 
)

Get formatted error messages to output (Used to show messages on html output).

Parameters
string$mesgstringError message
string[]$mesgarrayError messages array
int$keepembeddedSet to 1 in error message must be kept embedded into its html place (this disable jnotify)
Returns
string Return html output
See also
dol_print_error()
dol_htmloutput_mesg()

Definition at line 9781 of file functions.lib.php.

◆ get_htmloutput_mesg()

get_htmloutput_mesg (   $mesgstring = '',
  $mesgarray = [],
  $style = 'ok',
  $keepembedded = 0 
)

Get formatted messages to output (Used to show messages on html output).

This include also the translation of the message key.

Parameters
string$mesgstringMessage string or message key
string[]$mesgarrayArray of message strings or message keys
string$styleStyle of message output ('ok' or 'error')
int$keepembeddedSet to 1 in error message must be kept embedded into its html place (this disable jnotify)
Returns
string Return html output
See also
dol_print_error()
dol_htmloutput_errors()
setEventMessages()

Definition at line 9712 of file functions.lib.php.

◆ get_localtax()

get_localtax (   $vatrate,
  $local,
  $thirdparty_buyer = null,
  $thirdparty_seller = null,
  $vatnpr = 0 
)

Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller Note: This function applies same rules than get_default_tva.

Parameters
float | string$vatrateVat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
int$localLocal tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
Societe$thirdparty_buyerObject of buying third party
Societe$thirdparty_sellerObject of selling third party ($mysoc if not defined)
int$vatnprIf vat rate is NPR or not
Returns
int<0,0>|string 0 if not found, localtax rate if found
See also
get_default_tva()

Definition at line 6814 of file functions.lib.php.

◆ get_localtax_by_third()

get_localtax_by_third (   $local)

Get values of localtaxes (1 or 2) for company country for the common vat with the highest value.

Parameters
int$localLocalTax to get
Returns
string Values of localtax (Can be '20', '-19:-15:-9') or 'Error'

Definition at line 6967 of file functions.lib.php.

◆ get_product_localtax_for_country()

get_product_localtax_for_country (   $idprod,
  $local,
  $thirdpartytouse 
)

Return localtax vat rate of a product in a particular country or default country vat if product is unknown.

Parameters
int$idprodId of product
int$local1 for localtax1, 2 for localtax 2
Societe$thirdpartytouseThirdparty with a ->country_code defined (FR, US, IT, ...)
Returns
int Return integer <0 if KO, Vat rate if OK
See also
get_product_vat_for_country()

Definition at line 7237 of file functions.lib.php.

◆ get_product_vat_for_country()

get_product_vat_for_country (   $idprod,
  $thirdpartytouse,
  $idprodfournprice = 0 
)

Return vat rate of a product in a particular country, or default country vat if product is unknown.

Function called by get_default_tva(). Do not use this function directly, prefer to use get_default_tva().

Parameters
int$idprodId of product or 0 if not a predefined product
Societe$thirdpartytouseThirdparty with a ->country_code defined (FR, US, IT, ...)
int$idprodfournpriceId product_fournisseur_price (for "supplier" proposal/order/invoice)
Returns
float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
See also
get_default_tva(), get_product_localtax_for_country()

Definition at line 7142 of file functions.lib.php.

◆ getActionCommEcmList()

getActionCommEcmList (   $object)

getActionCommEcmList

Parameters
ActionComm$objectObject ActionComm
Returns
array<int,stdClass> Array of documents in index table

Definition at line 13512 of file functions.lib.php.

◆ getAdvancedPreviewUrl()

getAdvancedPreviewUrl (   $modulepart,
  $relativepath,
  $alldata = 0,
  $param = '' 
)

Return URL we can use for advanced preview links.

Parameters
string$modulepartpropal, facture, facture_fourn, ...
string$relativepathRelative path of docs.
int<0,1>$alldata Return array with all components (1 is recommended, then use a simple a href link with the class, target and mime attribute added. 'documentpreview' css class is handled by jquery code into main.inc.php)
string$paramMore param on http links
Returns
string|array{}|array{target:string,css:string,url:string,mime:string} Output string with href link or array with all components of link

Definition at line 11370 of file functions.lib.php.

◆ getArrayOfSocialNetworks()

getArrayOfSocialNetworks ( )

Get array of social network dictionary.

Returns
array<string,array{rowid:int,label:string,url:string,icon:string,active:int}> Array of Social Networks Dictionary

Definition at line 3772 of file functions.lib.php.

Referenced by User\update_ldap2dolibarr().

◆ getBrowserInfo()

getBrowserInfo (   $user_agent)

Return information about user browser.

Returns array with the following format: array( 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown) 'browserversion' => Browser version. Empty if unknown 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown) 'layout' => (tablet|phone|classic) 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile 'tablet' => true/false )

Parameters
string$user_agentContent of $_SERVER["HTTP_USER_AGENT"] variable
Returns
array{browsername:string,browserversion:string,browseros:string,browserua:string,layout:string,phone:string,tablet:bool} Check function documentation

Definition at line 515 of file functions.lib.php.

◆ getCommonSubstitutionArray()

getCommonSubstitutionArray (   $outputlangs,
  $onlykey = 0,
  $exclude = null,
  $object = null,
  $include = null 
)

Return array of possible common substitutions.

This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'

Parameters
Translate$outputlangsOutput language
int$onlykey1=Do not calculate some heavy values of keys (performance enhancement when we need only the keys), 2=Values are trunc and html sanitized (to use for help tooltip)
string[] | null$excludeArray of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
?CommonObject$object Object for keys on object
string[] | null$includeArray of family keys we want to include. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
Returns
array<string,string> Array of substitutions
See also
setSubstitFromObject() @phan-suppress PhanTypeArraySuspiciousNullable,PhanTypePossiblyInvalidDimOffset,PhanUndeclaredProperty

Definition at line 8571 of file functions.lib.php.

◆ getDictionaryValue()

getDictionaryValue (   $tablename,
  $field,
  $id,
  $checkentity = false,
  $rowidfield = 'rowid' 
)

Return the value of a filed into a dictionary for the record $id.

This also set all the values into a cache for a next search.

Parameters
string$tablenameName of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
string$fieldThe name of field where to find the value to return
int$idId of line record
bool$checkentityAdd filter on entity
string$rowidfieldName of the column rowid (to use for the filter on $id)
Returns
string The value of field $field. This also set $dictvalues cache.

Definition at line 11787 of file functions.lib.php.

Referenced by Holiday\approve().

◆ getDolGlobalInt()

getDolGlobalInt (   $key,
  $default = 0 
)

Return a Dolibarr global constant int value.

The constants $conf->global->xxx are loaded by the script master.inc.php included at begin of any PHP page.

Parameters
string$keykey to return value, return 0 if not set
int$defaultvalue to return
Returns
int
See also
getDolUserInt()

Definition at line 223 of file functions.lib.php.

Referenced by Propal\__construct(), Ldap\__construct(), mod_commande_fournisseur_muguet\__construct(), Product\check(), InvoiceListController\checkAccess(), OrderListController\checkAccess(), PropalListController\checkAccess(), MailmanSpip\connectSpip(), Societe\isACompany(), MailmanSpip\isSpipEnabled(), pricejs(), and Lettering\updateLettering().

◆ getDolGlobalString()

getDolGlobalString (   $key,
  $default = '' 
)

◆ getDoliDBInstance()

getDoliDBInstance (   $type,
  $host,
  $user,
  $pass,
  $name,
  $port 
)

Return a DoliDB instance (database handler).

Parameters
string$typeType of database (mysql, pgsql...)
string$hostAddress of database server
string$userAuthorized username
string$passPassword
string$nameName of database
int$portPort of database server
Returns
DoliDB A DoliDB instance

Definition at line 372 of file functions.lib.php.

Referenced by MailmanSpip\connectSpip(), and dolSessionOpen().

◆ getDolUserInt()

getDolUserInt (   $key,
  $default = 0,
  $tmpuser = null 
)

Return Dolibarr user constant int value.

Parameters
string$keykey to return value, return 0 if not set
int$defaultvalue to return
User$tmpuserTo get another user than current user
Returns
int

Definition at line 255 of file functions.lib.php.

◆ getDolUserString()

getDolUserString (   $key,
  $default = '',
  $tmpuser = null 
)

Return Dolibarr user constant string value.

Parameters
string$keykey to return value, return '' if not set
string$defaultvalue to return
User$tmpuserTo get another user than current user
Returns
string

Definition at line 237 of file functions.lib.php.

◆ getElementProperties()

getElementProperties (   $elementType)

Get an array with properties of an element.

Parameters
string$elementTypeElement type (Value of $object->element or value of $object->element$object->module). Example: 'action', 'facture', 'project', 'project_task' or 'myobject@mymodule' (or old syntax 'mymodule_myobject' like 'project_task')
Returns
array{module:string,element:string,table_element:string,subelement:string,classpath:string,classfile:string,classname:string,dir_output:string} array('module'=>, 'classpath'=>, 'element'=>, 'subelement'=>, 'classfile'=>, 'classname'=>, 'dir_output'=>)
See also
fetchObjectByElement(), getMultidirOutput()

Definition at line 12440 of file functions.lib.php.

◆ getEntity()

getEntity (   $element,
  $shared = 1,
  $currentobject = null 
)

Get list of entity id to use.

Parameters
string$elementCurrent element 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource', 'product', 'productprice', 'stock', 'bom', 'mo', 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various', 'categorie', 'bank_account', 'bank_account', 'adherent', 'user', 'commande', 'supplier_order', 'expedition', 'intervention', 'survey', 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project', 'email_template', 'event', 'donation' 'c_paiement', 'c_payment_term', ...
int<0,1>$shared 0=Return id of current entity only, 1=Return id of current entity + shared entities (default)
?CommonObject$currentobject Current object if needed
Returns
string Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )

Definition at line 398 of file functions.lib.php.

Referenced by PaymentTerm\fetch(), and Products\getAttributesByRefExt().

◆ getFieldErrorIcon()

getFieldErrorIcon (   $fieldValidationErrorMsg)

get field error icon

Parameters
string$fieldValidationErrorMsgmessage to add in tooltip
Returns
string html output

Definition at line 12313 of file functions.lib.php.

◆ getImageFileNameForSize()

getImageFileNameForSize (   $file,
  $extName,
  $extImgTarget = '' 
)

Return the filename of file to get the thumbs.

Parameters
string$fileOriginal filename (full or relative path)
string$extNameExtension to differentiate thumb file name ('', '_small', '_mini')
string$extImgTargetForce image extension for thumbs. Use '' to keep same extension than original image (default).
Returns
string New file name (full or relative path, including the thumbs/). May be the original path if no thumb can exists.

Definition at line 11319 of file functions.lib.php.

◆ getLanguageCodeFromCountryCode()

getLanguageCodeFromCountryCode (   $countrycode)

Return default language from country code.

Return null if not found.

Parameters
string$countrycodeCountry code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
Returns
?string Value of locale like 'en_US', 'fr_FR', ... or null if not found

Definition at line 10410 of file functions.lib.php.

◆ getLocalTaxesFromRate()

getLocalTaxesFromRate (   $vatrate,
  $local,
  $buyer,
  $seller,
  $firstparamisid = 0 
)

Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.

This does not take into account the seller setup if subject to vat or not, only country.

TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed. Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then provide the selected value to the function calcul_price_total.

Parameters
int | string$vatrateVAT ID or Rate+Code. Value can be value or the string with code into parenthesis or rowid if $firstparamisid is 1. Example: '8.5' or '8.5 (8.5NPR)' or 123.
int$localNumber of localtax (1 or 2, or 0 to return 1 & 2)
Societe$buyerCompany object
Societe$sellerCompany object
int$firstparamisid1 if first param is ID into table instead of Rate+code (use this if you can)
Returns
array{}|array{0:string,1:float,2:string,3:string}|array{0:string,1:float,2:string,3:float,4:string,5:string} array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
See also
getTaxesFromId()

Definition at line 7078 of file functions.lib.php.

◆ getMultidirOutput()

if (!function_exists( 'utf8_encode')) if (!function_exists( 'utf8_decode')) if (!function_exists( 'str_starts_with')) if (!function_exists( 'str_ends_with')) if (!function_exists( 'str_contains')) getMultidirOutput (   $object,
  $module = '',
  $forobject = 0,
  $mode = 'output' 
)

Return the full path of the directory where a module (or an object of a module) stores its files, Path may depends on the entity if a multicompany module is enabled.

Parameters
CommonObject$objectDolibarr common object
string$moduleOverride object element, for example to use 'mycompany' instead of 'societe'
int$forobjectReturn the more complete path for the given object instead of for the module only.
string$mode'output' or 'temp' or 'version'
Returns
string|null The path of the relative directory of the module
Since
Dolibarr V18

Definition at line 133 of file functions.lib.php.

◆ getMultidirTemp()

getMultidirTemp (   $object,
  $module = '',
  $forobject = 0 
)

Return the full path of the directory where a module (or an object of a module) stores its temporary files.

Path may depends on the entity if a multicompany module is enabled.

Parameters
CommonObject$objectDolibarr common object
string$moduleOverride object element, for example to use 'mycompany' instead of 'societe'
int$forobjectReturn the more complete path for the given object instead of for the module only.
Returns
string|null The path of the relative temp directory of the module

Definition at line 180 of file functions.lib.php.

◆ getMultidirVersion()

getMultidirVersion (   $object,
  $module = '',
  $forobject = 0 
)

Return the full path of the directory where a module (or an object of a module) stores its versioned files.

Path may depends on the entity if a multicompany module is enabled.

Parameters
CommonObject$objectDolibarr common object
string$moduleOverride object element, for example to use 'mycompany' instead of 'societe'
int$forobjectReturn the more complete path for the given object instead of for the module only.
Returns
string|null The path of the relative version directory of the module

Definition at line 194 of file functions.lib.php.

◆ getNonce()

getNonce ( )

Return a random string to be used as a nonce value for js.

Returns
string

Definition at line 12912 of file functions.lib.php.

◆ getPictoForType()

getPictoForType (   $key,
  $morecss = '' 
)

Return the picto for a data type.

Parameters
string$keyKey
string$morecssAdd more css to the object
Returns
string Pïcto for the key

Definition at line 4708 of file functions.lib.php.

◆ GETPOST()

GETPOST (   $paramname,
  $check = 'alphanohtml',
  $method = 0,
  $filter = null,
  $options = null,
  $noreplace = 0 
)

Return value of a param into GET or POST supervariable.

Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder'] Note: The property $user->default_values is loaded by main.php when loading the user.

Parameters
string$paramnameName of parameter to found
string$checkType of check ''=no check (deprecated) 'none'=no check (only for param that should have very rich content like passwords) 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array 'int'=check it's numeric (integer or float) 'intcomma'=check it's integer+comma ('1,2,3,4...') 'alpha'=Same than alphanohtml 'alphawithlgt'=alpha with lgt 'alphanohtml'=check there is no html content and no " and no ../ 'aZ'=check it's a-z only 'aZ09'=check it's simple alpha string (recommended for keys) 'aZ09arobase'=check it's a string for an element type ('myobject@mymodule') 'aZ09comma'=check it's a string for a sortfield or sortorder 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string) 'nohtml'=check there is no html content 'restricthtml'=check html content is restricted to some tags only 'custom'= custom filter specify $filter and $options)
int$methodType of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
?int$filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
mixed$optionsOptions to pass to filter_var when $check is set to 'custom'
int$noreplaceForce disable of replacement of xxx strings.
Returns
string|array Value found (string or array), or '' if check fails

Definition at line 745 of file functions.lib.php.

Referenced by FormListWebPortal\doActions().

◆ GETPOSTDATE()

GETPOSTDATE (   $prefix,
  $hourTime = '',
  $gm = 'auto' 
)

Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and optionally hour, minute, second) fields to return a timestamp.

Parameters
string$prefixPrefix used to build the date selector (for instance using Form::selectDate)
string$hourTime'getpost' to include hour, minute, second values from the HTTP request, 'XX:YY:ZZ' to set hour, minute, second respectively (for instance '23:59:59')
string$gmPassed to dol_mktime
Returns
int|string Date as a timestamp, '' or false if error

Definition at line 14298 of file functions.lib.php.

◆ GETPOSTFLOAT()

GETPOSTFLOAT (   $paramname,
  $rounding = '' 
)

Return the value of a $_GET or $_POST supervariable, converted into float.

Parameters
string$paramnameName of the $_GET or $_POST parameter
string | int$roundingType of rounding ('', 'MU', 'MT, 'MS', 'CU', 'CT', integer) {
See also
price2num()}
Returns
float Value converted into float
Since
Dolibarr V20

Definition at line 1082 of file functions.lib.php.

◆ GETPOSTINT()

GETPOSTINT (   $paramname,
  $method = 0 
)

Return the value of a $_GET or $_POST supervariable, converted into integer.

Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder'] Note: The property $user->default_values is loaded by main.php when loading the user.

Parameters
string$paramnameName of the $_GET or $_POST parameter
int<0,3>$method Type of method (0 = $_GET then $_POST, 1 = only $_GET, 2 = only $_POST, 3 = $_POST then $_GET)
Returns
int Value converted into integer

Definition at line 1068 of file functions.lib.php.

Referenced by FormSetupItem\setValueFromPost().

◆ GETPOSTISARRAY()

GETPOSTISARRAY (   $paramname,
  $method = 0 
)

Return true if the parameter $paramname is submit from a POST OR GET as an array.

Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string

Parameters
string$paramnameName or parameter to test
int<0,3>$method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
Returns
bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)

Definition at line 698 of file functions.lib.php.

◆ GETPOSTISSET()

GETPOSTISSET (   $paramname)

Return true if we are in a context of submitting the parameter $paramname from a POST of a form.

Warning: For action=add, use: $var = GETPOST('var'); // No GETPOSTISSET, so GETPOST always called and default value is retrieved if not a form POST, and value of form is retrieved if it is a form POST. For action=update, use: $var = GETPOSTISSET('var') ? GETPOST('var') : $object->var;

Parameters
string$paramnameName or parameter to test
Returns
boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)

Definition at line 645 of file functions.lib.php.

◆ getTaxesFromId()

getTaxesFromId (   $vatrate,
  $buyer = null,
  $seller = null,
  $firstparamisid = 1 
)

Get tax (VAT) main information from Id.

You can also call getLocalTaxesFromRate() after to get only localtax fields.

Parameters
int | string$vatrateVAT ID or Rate. Value can be value or the string with code into parenthesis or rowid if $firstparamisid is 1. Example: '8.5' or '8.5 (8.5NPR)' or 123.
Societe$buyerCompany object
Societe$sellerCompany object
int<0,1>$firstparamisid 1 if first param is id into table (use this if you can)
Returns
array{}|array{rowid:int,code:string,rate:float,localtax1:float,localtax1_type:string,localtax2:float,localtax2_type:string,npr:float,accountancy_code_sell:string,accountancy_code_buy:string} array('rowid'=> , 'code'=> ...)
See also
getLocalTaxesFromRate()

Definition at line 7004 of file functions.lib.php.

◆ getTimelineIcon()

getTimelineIcon (   $actionstatic,
$histo,
  $key 
)

Get timeline icon.

Parameters
ActionComm$actionstaticactioncomm
array<int,array{percent:int}>$histo histo
int$keykey
Returns
string String with timeline icon
Deprecated:
Use actioncomm->getPictoType() instead

Definition at line 13448 of file functions.lib.php.

◆ getTitleFieldOfList()

getTitleFieldOfList (   $name,
  $thead = 0,
  $file = "",
  $field = "",
  $begin = "",
  $moreparam = "",
  $moreattrib = "",
  $sortfield = "",
  $sortorder = "",
  $prefix = "",
  $disablesortlink = 0,
  $tooltip = '',
  $forcenowrapcolumntitle = 0 
)

Get title line of an array.

Parameters
string$nameTranslation key of field to show or complete HTML string to show
int$thead0=To use with standard table format, 1=To use inside <thead>

, 2=To use with

Parameters
string$fileUrl used when we click on sort picto
string$fieldField to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
string$begin("" by default)
string$moreparamAdd more parameters on sort url links ("" by default)
string$moreattribAdd more attributes on th ("" by default). To add more css class, use param $prefix.
string$sortfieldCurrent field used to sort (Ex: 'd.datep,d.id')
string$sortorderCurrent sort order (Ex: 'asc,desc')
string$prefixPrefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
int$disablesortlink1=Disable sort link
string$tooltipTooltip
int$forcenowrapcolumntitleNo need for use 'wrapcolumntitle' css style
Returns
string

Definition at line 5978 of file functions.lib.php.

◆ getUserRemoteIP()

getUserRemoteIP ( )

Return the IP of remote user.

Take HTTP_X_FORWARDED_FOR (defined when using proxy) Then HTTP_CLIENT_IP if defined (rare) Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)

Returns
string Ip of remote user.

Definition at line 4322 of file functions.lib.php.

Referenced by dolSessionWrite().

◆ img_action()

img_action (   $titlealt,
  $numaction,
  $picto = '',
  $moreatt = '' 
)

Show logo action.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$numactionAction id or code to show
string$pictoName of image file to show ('filenew', ...) If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory. Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
string$moreattMore attributes
Returns
string Return an img tag

Definition at line 5216 of file functions.lib.php.

◆ img_allow()

img_allow (   $allow,
  $titlealt = 'default' 
)

Show tick logo if allowed.

Parameters
string$allowAllow
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
Returns
string Return img tag

Definition at line 5591 of file functions.lib.php.

◆ img_credit_card()

img_credit_card (   $brand,
  $morecss = null 
)

Return image of a credit card according to its brand name.

Parameters
string$brandBrand name of credit card
string$morecssMore CSS
Returns
string Return img tag

Definition at line 5613 of file functions.lib.php.

◆ img_delete()

img_delete (   $titlealt = 'default',
  $other = 'class="pictodelete"',
  $morecss = '' 
)

Show delete logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$otherAdd more attributes on img
string$morecssMore CSS
Returns
string Retourne tag img

Definition at line 5349 of file functions.lib.php.

◆ img_down()

img_down (   $titlealt = 'default',
  $selected = 0,
  $moreclass = '' 
)

Show down arrow logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
int$selectedSelected
string$moreclassAdd more CSS classes
Returns
string Return img tag

Definition at line 5516 of file functions.lib.php.

◆ img_edit()

img_edit (   $titlealt = 'default',
  $float = 0,
  $other = '' 
)

Show logo edit/modify fiche.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
integer$floatIf you have to put the style "float: right"
string$otherAdd more attributes on img
Returns
string Return tag img

Definition at line 5309 of file functions.lib.php.

◆ img_edit_add()

img_edit_add (   $titlealt = 'default',
  $other = '' 
)

Show logo +.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$otherAdd more attributes on img
Returns
string Return tag img

Definition at line 5273 of file functions.lib.php.

◆ img_edit_remove()

img_edit_remove (   $titlealt = 'default',
  $other = '' 
)

Show logo -.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$otherAdd more attributes on img
Returns
string Return tag img

Definition at line 5290 of file functions.lib.php.

◆ img_error()

img_error (   $titlealt = 'default')

Show error logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
Returns
string Return img tag

Definition at line 5459 of file functions.lib.php.

◆ img_help()

img_help (   $usehelpcursor = 1,
  $usealttitle = 1 
)

Show help logo with cursor "?".

Parameters
int$usehelpcursor1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
int | string$usealttitleText to use as alt title
Returns
string Return tag img

Definition at line 5401 of file functions.lib.php.

◆ img_info()

img_info (   $titlealt = 'default')

Show info logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
Returns
string Return img tag

Definition at line 5422 of file functions.lib.php.

◆ img_left()

img_left (   $titlealt = 'default',
  $selected = 0,
  $moreatt = '' 
)

Show left arrow logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
int$selectedSelected
string$moreattAdd more attribute on img tag (For example 'style="float: right"')
Returns
string Return img tag

Definition at line 5554 of file functions.lib.php.

◆ img_mime()

img_mime (   $file,
  $titlealt = '',
  $morecss = '' 
)

Show MIME img of a file.

Parameters
string$fileFilename
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$morecssMore css
Returns
string Return img tag

Definition at line 5646 of file functions.lib.php.

◆ img_next()

img_next (   $titlealt = 'default',
  $moreatt = '' 
)

Show next logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$moreattAdd more attribute on img tag (For example 'style="float: right"')
Returns
string Return img tag

Definition at line 5477 of file functions.lib.php.

◆ img_object()

img_object (   $titlealt,
  $picto,
  $moreatt = '',
  $pictoisfullpath = 0,
  $srconly = 0,
  $notitle = 0 
)

Show a picto called object_picto (generic function)

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$pictoName of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...) For external modules use imagename@mymodule to search into directory "img" of module.
string$moreattAdd more attribute on img tag (ie: class="datecallink")
int$pictoisfullpathIf 1, image path is a full path
int$srconlyReturn only content of the src attribute of img.
int$notitle1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
Returns
string Return img tag
See also
img_picto(), img_picto_common()

Definition at line 5130 of file functions.lib.php.

◆ img_pdf()

img_pdf (   $titlealt = 'default',
  $size = 3 
)

Show pdf logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
int$sizeTaille de l'icone : 3 = 16x16px , 2 = 14x14px
Returns
string Retourne tag img

Definition at line 5255 of file functions.lib.php.

◆ img_picto()

img_picto (   $titlealt,
  $picto,
  $moreatt = '',
  $pictoisfullpath = 0,
  $srconly = 0,
  $notitle = 0,
  $alt = '',
  $morecss = '',
  $marginleftonlyshort = 2 
)

Show picto whatever it's its name (generic function)

Parameters
string$titlealtText on title tag for tooltip. Not used if param notitle is set to 1.
string$pictoName of image file to show ('filenew', ...). For font awesome icon (example 'user'), you can use picto_nocolor to not have the color of picto forced. If no extension provided and it is not a font awesome icon, we use '.png'. Image must be stored into theme/xxx/img directory. Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1) Example: fontawesome_envelope-open-text_fas_red_1em if you want to use fontaweseome icons: fontawesome_<icon-name>_<style>_<color>_<size> (only icon-name is mandatory)
string$moreattAdd more attribute on img tag (For example 'class="pictofixedwidth"')
int<0,1>$pictoisfullpath If true or 1, image path is a full path, 0 if not
int$srconlyReturn only content of the src attribute of img.
int$notitle1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
string$altForce alt for bind people
string$morecssAdd more class css on img tag (For example 'myclascss').
int$marginleftonlyshort1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No margin left. Works for fontawesome picto only.
Returns
string Return img tag
See also
img_object(), img_picto_common()

Definition at line 4770 of file functions.lib.php.

◆ img_picto_common()

img_picto_common (   $titlealt,
  $picto,
  $moreatt = '',
  $pictoisfullpath = 0,
  $notitle = 0 
)

Show picto (generic function)

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$pictoName of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory.
string$moreattAdd more attribute on img tag
int$pictoisfullpathIf 1, image path is a full path
int$notitle1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
Returns
string Return img tag
See also
img_object(), img_picto()

Definition at line 5178 of file functions.lib.php.

◆ img_previous()

img_previous (   $titlealt = 'default',
  $moreatt = '' 
)

Show previous logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$moreattAdd more attribute on img tag (For example 'style="float: right"')
Returns
string Return img tag

Definition at line 5496 of file functions.lib.php.

◆ img_printer()

img_printer (   $titlealt = "default",
  $other = '' 
)

Show printer logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$otherAdd more attributes on img
Returns
string Retourne tag img

Definition at line 5367 of file functions.lib.php.

◆ img_right()

img_right (   $titlealt = 'default',
  $selected = 0,
  $moreatt = '' 
)

Show right arrow logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
int$selectedSelected
string$moreattAdd more attribute on img tag (For example 'style="float: right"')
Returns
string Return img tag

Definition at line 5573 of file functions.lib.php.

◆ img_search()

img_search (   $titlealt = 'default',
  $other = '' 
)

Show search logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$otherAdd more attributes on img
Returns
string Retourne tag img

Definition at line 5670 of file functions.lib.php.

◆ img_searchclear()

img_searchclear (   $titlealt = 'default',
  $other = '' 
)

Show search logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$otherAdd more attributes on img
Returns
string Retourne tag img

Definition at line 5693 of file functions.lib.php.

◆ img_split()

img_split (   $titlealt = 'default',
  $other = 'class="pictosplit"' 
)

Show split logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$otherAdd more attributes on img
Returns
string Retourne tag img

Definition at line 5383 of file functions.lib.php.

◆ img_up()

img_up (   $titlealt = 'default',
  $selected = 0,
  $moreclass = '' 
)

Show top arrow logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
int$selectedSelected
string$moreclassAdd more CSS classes
Returns
string Return img tag

Definition at line 5535 of file functions.lib.php.

◆ img_view()

img_view (   $titlealt = 'default',
  $float = 0,
  $other = 'class="valignmiddle"' 
)

Show logo view card.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
integer$floatIf you have to put the style "float: right"
string$otherAdd more attributes on img
Returns
string Return tag img

Definition at line 5328 of file functions.lib.php.

◆ img_warning()

img_warning (   $titlealt = 'default',
  $moreatt = '',
  $morecss = 'pictowarning' 
)

Show warning logo.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string$moreattAdd more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
string$morecssAdd more CSS
Returns
string Return img tag

Definition at line 5441 of file functions.lib.php.

◆ img_weather()

img_weather (   $titlealt,
  $picto,
  $moreatt = '',
  $pictoisfullpath = 0,
  $morecss = '' 
)

Show weather picto.

Parameters
string$titlealtText on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
string | int$pictoName of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory. Or level of meteo image (0-4).
string$moreattAdd more attribute on img tag
int$pictoisfullpathIf 1, image path is a full path
string$morecssMore CSS
Returns
string Return img tag
See also
img_object(), img_picto()

Definition at line 5150 of file functions.lib.php.

◆ info_admin()

info_admin (   $text,
  $infoonimgalt = 0,
  $nodiv = 0,
  $admin = '1',
  $morecss = 'hideonsmartphone',
  $textfordropdown = '' 
)

Show information in HTML for admin users or standard users.

Parameters
string$textText info
integer$infoonimgaltInfo is shown only on alt of star picto, otherwise it is show on output after the star picto
int$nodivNo div
string$admin'1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
string$morecssMore CSS ('', 'warning', 'error')
string$textfordropdownShow a text to click to dropdown the info box.
Returns
string String with info text

Definition at line 5720 of file functions.lib.php.

◆ isAFileWithExecutableContent()

isAFileWithExecutableContent (   $filename)

Return if a file can contains executable content.

Parameters
string$filenameFile name to test
Returns
boolean True if yes, False if no

Definition at line 12874 of file functions.lib.php.

◆ isASecretKey()

isASecretKey (   $keyname)

Return if string has a name dedicated to store a secret.

Parameters
string$keynameName of key to test
Returns
boolean True if key is used to store a secret

Definition at line 478 of file functions.lib.php.

◆ isDolTms()

isDolTms (   $timestamp)

isDolTms check if a timestamp is valid.

Parameters
int | string | null$timestamptimestamp to check
Returns
bool

Definition at line 348 of file functions.lib.php.

◆ isHTTPS()

isHTTPS ( )

Return if we are using a HTTPS connection Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy) Take HTTP_X_FORWARDED_PROTO (defined when using proxy) Then HTTP_X_FORWARDED_SSL.

Returns
boolean True if user is using HTTPS

Definition at line 4348 of file functions.lib.php.

◆ isModEnabled()

isModEnabled (   $module)

Is Dolibarr module enabled.

Parameters
string$moduleModule name to check
Returns
boolean True if module is enabled

Definition at line 305 of file functions.lib.php.

Referenced by Contact\__construct(), DolibarrDebugBar\__construct(), pdf_eagle\atLeastOneBatch(), InvoiceListController\checkAccess(), OrderListController\checkAccess(), PropalListController\checkAccess(), ExpeditionLigne\delete(), User\fetch(), and User\loadStateBoard().

◆ isOnlyOneLocalTax()

isOnlyOneLocalTax (   $local)

Return true if LocalTax (1 or 2) is unique.

Example: If localtax1 is 5 on line with highest common vat rate, return true Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false

Parameters
int$localLocal tax to test (1 or 2)
Returns
boolean True if LocalTax have multiple values, False if not

Definition at line 6948 of file functions.lib.php.

◆ isStringVarMatching()

isStringVarMatching (   $var,
  $regextext,
  $matchrule = 1 
)

Check if a variable with name $var startx with $text.

Can be used to forge dol_eval() conditions.

Parameters
string$varVariable
string$regextextText that must be a valid regex string
int<0,1>$matchrule 1=Test if start with, 0=Test if equal
Returns
boolean|string True or False, text if bad usage.

Definition at line 10106 of file functions.lib.php.

◆ isValidEmail()

isValidEmail (   $address,
  $acceptsupervisorkey = 0,
  $acceptuserkey = 0 
)

Return true if email syntax is ok.

Parameters
string$addressemail (Ex: "toto@example.com". Long form "John Do <johndo@example.com>" will be false)
int$acceptsupervisorkeyIf 1, the special string 'SUPERVISOREMAIL' is also accepted as valid
int$acceptuserkeyIf 1, the special string 'USER_EMAIL' is also accepted as valid
Returns
boolean true if email syntax is OK, false if KO or empty string
See also
isValidMXRecord()

Definition at line 4494 of file functions.lib.php.

Referenced by dolObfuscateEmail().

◆ isValidMXRecord()

isValidMXRecord (   $domain)

Return if the domain name has a valid MX record.

WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr

Parameters
string$domainDomain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
Returns
int -1 if error (function not available), 0=Not valid, 1=Valid
See also
isValidEmail() @suppress PhanDeprecatedFunctionInternal Error in Phan plugins incorrectly tags some functions here

Definition at line 4518 of file functions.lib.php.

◆ isValidPhone()

isValidPhone (   $phone)

Return true if phone number syntax is ok TODO Decide what to do with this.

Parameters
string$phonephone (Ex: "0601010101")
Returns
boolean true if phone syntax is OK, false if KO or empty string

Definition at line 4550 of file functions.lib.php.

◆ isVisibleToUserType()

isVisibleToUserType (   $type_user,
$menuentry,
$listofmodulesforexternal 
)

Function to test if an entry is enabled or not.

Parameters
int<0,1>$type_user 0=We test for internal user, 1=We test for external user
array{enabled:int<0,1>,module:string,perms:string}$menuentry Array for feature entry to test
string[]$listofmodulesforexternalArray with list of modules allowed to external users
Returns
int<0,2> 0=Hide, 1=Show, 2=Show gray

Definition at line 11866 of file functions.lib.php.

◆ jsonOrUnserialize()

jsonOrUnserialize (   $stringtodecode)

Decode an encode string.

The string can be encoded in json format (recommended) or with serialize (avoid this)

Parameters
string$stringtodecodeString to decode (json or serialize coded)
Returns
mixed The decoded object.

Definition at line 13132 of file functions.lib.php.

◆ load_fiche_titre()

load_fiche_titre (   $title,
  $morehtmlright = '',
  $picto = 'generic',
  $pictoisfullpath = 0,
  $id = '',
  $morecssontable = '',
  $morehtmlcenter = '' 
)

Load a title with picto.

Parameters
string$titleTitle to show (HTML sanitized content)
string$morehtmlrightAdded message to show on right
string$pictoIcon to use before title (should be a 32x32 transparent png file)
int$pictoisfullpath1=Icon name is a full absolute url of image
string$idTo force an id on html objects
string$morecssontableMore css on table
string$morehtmlcenterAdded message to show on center
Returns
string
See also
print_barre_liste()

Definition at line 6137 of file functions.lib.php.

◆ make_substitutions()

make_substitutions (   $text,
  $substitutionarray,
  $outputlangs = null,
  $converttextinhtmlifnecessary = 0 
)

Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval), and texts like __(TranslationKey|langfile)__ and [ConstantKey] are also replaced.

Example of usage: $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty); complete_substitutions_array($substitutionarray, $langs, $thirdparty); $mesg = make_substitutions($mesg, $substitutionarray, $langs);

Parameters
string$textSource string in which we must do substitution
array<string,string>$substitutionarray Array with key->val to substitute. Example: array('MYKEY' => 'MyVal', ...)
?Translate$outputlangs Output language
int$converttextinhtmlifnecessary0=Convert only value into HTML if text is already in HTML 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
Returns
string Output string after substitutions
See also
complete_substitutions_array(), getCommonSubstitutionArray()

Definition at line 9265 of file functions.lib.php.

◆ natural_search()

natural_search (   $fields,
  $value,
  $mode = 0,
  $nofirstand = 0 
)

Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)

Parameters
string | string[]$fieldsString or array of strings, filled with the name of all fields in the SQL query we must check (combined with a OR). Example: array("p.field1","p.field2")
string$valueThe value to look for. If param $mode is 0, can contains several keywords separated with a space or | like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2 or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2 If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < -1000" If param $mode is 2 or -2, can contains a list of int id separated by comma like "1,3,4" If param $mode is 3 or -3, can contains a list of string separated by comma like "a,b,c".
integer$mode0=value is list of keyword strings, 1=value is a numeric test (Example ">5.5 <10"), 2=value is a list of ID separated with comma (Example '1,3,4'), -2 is for exclude list, 3=value is list of string separated with comma (Example 'text 1,text 2'), -3 if for exclude list, 4=value is a list of ID separated with comma (Example '2,7') to be used to search into a multiselect string '1,2,3,4'
integer$nofirstand1=Do not output the first 'AND'
Returns
string $res The statement to append to the SQL query
See also
dolSqlDateFilter()
forgeSQLFromUniversalSearchCriteria()

Definition at line 11119 of file functions.lib.php.

◆ newToken()

newToken ( )

Return the value of token currently saved into session with name 'newtoken'.

This token must be send by any POST as it will be used by next page for comparison with value in session.

Since
Dolibarr v10.0.7
Returns
string

Definition at line 12890 of file functions.lib.php.

◆ num2Alpha()

num2Alpha (   $n)

Return a numeric value into an Excel like column number.

So 0 return 'A', 1 returns 'B'..., 26 return 'AA'

Parameters
int | string$nNumeric value
Returns
string Column in Excel format

Definition at line 490 of file functions.lib.php.

◆ picto_from_langcode()

picto_from_langcode (   $codelang,
  $moreatt = '',
  $notitlealt = 0 
)

Return img flag of country for a language code or country code.

Parameters
string$codelangLanguage code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
string$moreattAdd more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
int<0,1>$notitlealt No title alt
Returns
string HTML img string with flag.

Definition at line 10359 of file functions.lib.php.

◆ picto_required()

picto_required ( )

Return picto saying a field is required.

Returns
string Chaine avec picto obligatoire

Definition at line 7717 of file functions.lib.php.

◆ price()

price (   $amount,
  $form = 0,
  $outlangs = '',
  $trunc = 1,
  $rounding = -1,
  $forcerounding = -1,
  $currency_code = '' 
)

Function to format a value into an amount for visual output Function used into PDF and HTML pages.

Parameters
string | float$amountAmount value to format
int<0,1>$form Type of formatting: 1=HTML, 0=no formatting (no by default)
Translate | string | null$outlangsObject langs for output. '' use default lang. 'none' use international separators.
int$trunc1=Truncate if there is more decimals than MAIN_MAX_DECIMALS_SHOWN (default), 0=Does not truncate. Deprecated because amount are rounded (to unit or total amount accuracy) before being inserted into database or after a computation, so this parameter should be useless.
int$roundingMINIMUM number of decimal to show: 0=no change, -1=we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
int | string$forceroundingMAXIMUM number of decimal to forcerounding decimal: -1=no change, 'MU' or 'MT' or a numeric to round to MU or MT or to a given number of decimal
string$currency_codeTo add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
Returns
string String with formatted amount
See also
price2num() Revert function of price

Definition at line 6505 of file functions.lib.php.

◆ price2num()

price2num (   $amount,
  $rounding = '',
  $option = 0 
)

Function that return a number with universal decimal format (decimal separator is '.

') from an amount typed by a user. Function to use on each input amount before any numeric test or database insert. A better name for this function should be roundtext2num().

Parameters
string | float$amountAmount to convert/clean or round
string | int$rounding''=No rounding 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT) 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT) 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK) 'CU'=Round to Max unit price of foreign currency accuracy 'CT'=Round to Max for totals with Tax of foreign currency accuracy Numeric = Nb of digits for rounding (For example 2 for a percentage)
int$optionPut 1 if you know that content is already universal format number (so no correction on decimal will be done) Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
Returns
string Amount with universal numeric format (Example: '99.99999'), or error message. If conversion fails to return a numeric, it returns:
  • text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  • '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9' Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num(). If amount is null or '', it returns '' if $rounding = '', it returns '0' if $rounding is defined.
See also
price() Opposite function of price2num

Definition at line 6632 of file functions.lib.php.

Referenced by PaymentVarious\check(), ChargeSociales\check(), AccountancyImport\cleanAmount(), CommonInvoice\getRemainToPay(), ExpenseReportLine\insert(), Commande\setDiscount(), Facture\setDiscount(), Deplacement\update(), ExpeditionLigne\update(), CurrencyRate\update(), and SupplierProposal\updatePriceFournisseur().

◆ print_barre_liste()

print_barre_liste (   $title,
  $page,
  $file,
  $options = '',
  $sortfield = '',
  $sortorder = '',
  $morehtmlcenter = '',
  $num = -1,
  $totalnboflines = '',
  $picto = 'generic',
  $pictoisfullpath = 0,
  $morehtmlright = '',
  $morecss = '',
  $limit = -1,
  $hideselectlimit = 0,
  $hidenavigation = 0,
  $pagenavastextinput = 0,
  $morehtmlrightbeforearrow = '' 
)

Print a title with navigation controls for pagination.

Parameters
string$titleTitle to show (required)
int | null$pageNumero of page to show in navigation links (required)
string$fileUrl of page (required)
string$optionsMore parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
string$sortfieldField to sort on ('' by default)
string$sortorderOrder to sort ('' by default)
string$morehtmlcenterString in the middle ('' by default). We often find here string $massaction coming from $form->selectMassAction()
int$numNumber of records found by select with limit+1
int | string$totalnboflinesTotal number of records/lines for all pages (if known). Use a negative value of number to not show number. Use '' if unknown.
string$pictoIcon to use before title (should be a 32x32 transparent png file)
int$pictoisfullpath1=Icon name is a full absolute url of image
string$morehtmlrightMore html to show (after arrows)
string$morecssMore css to the table
int$limitMax number of lines (-1 = use default, 0 = no limit, > 0 = limit).
int$hideselectlimitForce to hide select limit
int$hidenavigationForce to hide the arrows and page for navigation
int$pagenavastextinput1=Do not suggest list of pages to navigate but suggest the page number into an input field.
string$morehtmlrightbeforearrowMore html to show (before arrows)
Returns
void

Definition at line 6190 of file functions.lib.php.

◆ print_date_range()

print_date_range (   $date_start,
  $date_end,
  $format = '',
  $outputlangs = null 
)

Format output for start and end date.

Parameters
int$date_startStart date
int$date_endEnd date
string$formatOutput format
Translate$outputlangsOutput language
Returns
void

Definition at line 9506 of file functions.lib.php.

◆ print_fiche_titre()

print_fiche_titre (   $title,
  $mesg = '',
  $picto = 'generic',
  $pictoisfullpath = 0,
  $id = '' 
)

Show a title with picto.

Parameters
string$titleTitle to show
string$mesgAdded message to show on right
string$pictoIcon to use before title (should be a 32x32 transparent png file)
int$pictoisfullpath1=Icon name is a full absolute url of image
string$idTo force an id on html objects by example id="name" where name is id
Returns
void
Deprecated:
Use print load_fiche_titre instead

Definition at line 6119 of file functions.lib.php.

◆ print_fleche_navigation()

print_fleche_navigation (   $page,
  $file,
  $options = '',
  $nextpage = 0,
  $betweenarrows = '',
  $afterarrows = '',
  $limit = -1,
  $totalnboflines = 0,
  $hideselectlimit = 0,
  $beforearrows = '',
  $hidenavigation = 0 
)

Function to show navigation arrows into lists.

Parameters
int$pageNumber of page
string$filePage URL (in most cases provided with $_SERVER["PHP_SELF"])
string$optionsOther url parameters to propagate ("" by default, may include sortfield and sortorder)
integer$nextpageDo we show a next page button
string$betweenarrowsHTML content to show between arrows. MUST contains ' ' tags or ' '.
string$afterarrowsHTML content to show after arrows. Must NOT contains ' ' tags.
int$limitMax nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
int$totalnboflinesTotal number of records/lines for all pages (if known)
int$hideselectlimitForce to hide select limit
string$beforearrowsHTML content to show before arrows. Must NOT contains ' ' tags.
int$hidenavigationForce to hide the switch mode view and the navigation tool (hide limit section, html in $betweenarrows and $afterarrows but not $beforearrows)
Returns
void

Definition at line 6351 of file functions.lib.php.

◆ print_liste_field_titre()

print_liste_field_titre (   $name,
  $file = "",
  $field = "",
  $begin = "",
  $moreparam = "",
  $moreattrib = "",
  $sortfield = "",
  $sortorder = "",
  $prefix = "",
  $tooltip = "",
  $forcenowrapcolumntitle = 0 
)

Show title line of an array.

Parameters
string$nameLabel of field
string$fileUrl used when we click on sort picto
string$fieldField to use for new sorting
string$begin("" by default)
string$moreparamAdd more parameters on sort url links ("" by default)
string$moreattribOptions of attribute td ("" by default)
string$sortfieldCurrent field used to sort
string$sortorderCurrent sort order
string$prefixPrefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
string$tooltipTooltip
int$forcenowrapcolumntitleNo need for use 'wrapcolumntitle' css style
Returns
void

Definition at line 5955 of file functions.lib.php.

◆ print_titre()

print_titre (   $title)

Show a title.

Parameters
string$titleTitle to show
Returns
void
Deprecated:
Use load_fiche_titre instead
See also
load_fiche_titre()

Definition at line 6101 of file functions.lib.php.

◆ printCommonFooter()

printCommonFooter (   $zone = 'private')

Print common footer : conf->global->MAIN_HTML_FOOTER js for switch of menu hider js for conf->global->MAIN_GOOGLE_AN_ID js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"] js for conf->logbuffer.

Parameters
string$zone'private' (for private pages) or 'public' (for public pages)
Returns
void

Definition at line 10822 of file functions.lib.php.

Referenced by llxFooterVierge().

◆ readfileLowMemory()

readfileLowMemory (   $fullpath_original_file_osencoded,
  $method = -1 
)

Return a file on output using a low memory.

It can return very large files with no need of memory. WARNING: This close output buffers.

Parameters
string$fullpath_original_file_osencodedFull path of file to return.
int<-1,2>$method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
Returns
void

Definition at line 13058 of file functions.lib.php.

◆ recordNotFound()

recordNotFound (   $message = '',
  $printheader = 1,
  $printfooter = 1,
  $showonlymessage = 0,
  $params = null 
)

Displays an error page when a record is not found.

It allows customization of the message, whether to include the header and footer, and if only the message should be shown without additional details. The function also supports executing additional hooks for customized handling of error pages.

Parameters
string$messageCustom error message to display. If empty, a default "Record Not Found" message is shown.
int<0,1>$printheader Determines if the page header should be printed (1 = yes, 0 = no).
int<0,1>$printfooter Determines if the page footer should be printed (1 = yes, 0 = no).
int<0,1>$showonlymessage If set to 1, only the error message is displayed without any additional information or hooks.
mixed$paramsOptional parameters to pass to hooks for further processing or customization. @global Conf $conf Dolibarr configuration object (global) @global DoliDB $db Database connection object (global) @global User $user Current user object (global) @global Translate $langs Language translation object, initialized within the function if not already. @global HookManager $hookmanager Hook manager object, initialized within the function if not already for executing hooks. @global string $action Current action, can be modified by hooks. @global object $object Current object, can be modified by hooks.
Returns
void This function terminates script execution after outputting the error page.

Definition at line 14369 of file functions.lib.php.

◆ roundUpToNextMultiple()

roundUpToNextMultiple (   $n,
  $x = 5 
)

Round to next multiple.

Parameters
float$nNumber to round up
int$xMultiple. For example 60 to round up to nearest exact minute for a date with seconds.
Returns
int Value rounded.

Definition at line 11907 of file functions.lib.php.

◆ sanitizeVal()

sanitizeVal (   $out = '',
  $check = 'alphanohtml',
  $filter = null,
  $options = null 
)

Return a sanitized or empty value after checking value against a rule.

Parameters
string | array$outValue to check/clear.
string$checkType of check/sanitizing
int$filterFilter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
mixed$optionsOptions to pass to filter_var when $check is set to 'custom'
Returns
string|array Value sanitized (string or array). It may be '' if format check fails.

Return a prefix to use for this Dolibarr instance, for session/cookie names or email id. The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir or two instances in same virtual servers. This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.

Parameters
string$mode'' (prefix for session name) or 'email' (prefix for email id)
Returns
string A calculated prefix @phan-suppress PhanRedefineFunction - Also defined in webportal.main.inc.php

Definition at line 1113 of file functions.lib.php.

Referenced by Export\build_filterQuery().

◆ setEntity()

setEntity (   $currentobject)

Set entity id to use when to create an object.

Parameters
CommonObject$currentobjectCurrent object
Returns
int Entity id to use ( eg. entity = '.setEntity($object) )

Definition at line 461 of file functions.lib.php.

◆ setEventMessage()

setEventMessage (   $mesgs,
  $style = 'mesgs',
  $noduplicate = 0 
)

Set event message in dol_events session object.

Will be output by calling dol_htmloutput_events. Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function. Note: Prefer to use setEventMessages instead.

Parameters
string | string[]$mesgsMessage string or array
string$styleWhich style to use ('mesgs' by default, 'warnings', 'errors')
int$noduplicate1 means we do not add the message if already present in session stack
Returns
void
See also
dol_htmloutput_events()

Definition at line 9599 of file functions.lib.php.

◆ setEventMessages()

setEventMessages (   $mesg,
  $mesgs,
  $style = 'mesgs',
  $messagekey = '',
  $noduplicate = 0 
)

Set event messages in dol_events session object.

Will be output by calling dol_htmloutput_events. Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.

Parameters
string | null$mesgMessage string
string[] | null$mesgsMessage array
string$styleWhich style to use ('mesgs' by default, 'warnings', 'errors')
string$messagekeyA key to be used to allow the feature "Never show this message during this session again"
int$noduplicate1 means we do not add the message if already present in session stack
Returns
void
See also
dol_htmloutput_events()

Definition at line 9637 of file functions.lib.php.

Referenced by Societe\setParent().

◆ show_actions_messaging()

show_actions_messaging (   $conf,
  $langs,
  $db,
  $filterobj,
  $objcon = null,
  $noprint = 0,
  $actioncode = '',
  $donetodo = 'done',
  $filters = array(),
  $sortfield = 'a.datep,
a.id'  ,
  $sortorder = 'DESC' 
)

Show html area with actions in messaging format.

Note: Global parameter $param must be defined.

Parameters
Conf$confObject conf
Translate$langsObject langs
DoliDB$dbObject db
?CommonObject$filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object
?Contact$objcon Filter on object contact to filter events on a contact
int$noprintReturn string but does not output it
string$actioncodeFilter on actioncode
string$donetodoFilter on event 'done' or 'todo' or ''=nofilter (all).
array<string,string>$filters Filter on other fields
string$sortfieldSort field
string$sortorderSort order
Returns
string|void Return html part or void if noprint is 1

Definition at line 13554 of file functions.lib.php.

◆ showDimensionInBestUnit()

showDimensionInBestUnit (   $dimension,
  $unit,
  $type,
  $outputlangs,
  $round = -1,
  $forceunitoutput = 'no',
  $use_short_label = 0 
)

Output a dimension with best unit.

Parameters
float$dimensionDimension
int$unitUnit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
string$type'weight', 'volume', ...
Translate$outputlangsTranslate language object
int$round-1 = non rounding, x = number of decimal
string$forceunitoutput'no' or numeric (-3, -6, ...) compared to $unit (In most case, this value is value defined into $conf->global->MAIN_WEIGHT_DEFAULT_UNIT)
int$use_short_label1=Use short label ('g' instead of 'gram'). Short labels are not translated.
Returns
string String to show dimensions

Definition at line 6764 of file functions.lib.php.

◆ showDirectDownloadLink()

showDirectDownloadLink (   $object)

Return string with full Url.

The file qualified is the one defined by relative path in $object->last_main_doc

Parameters
CommonObject$objectObject
Returns
string Url string

Definition at line 11293 of file functions.lib.php.

◆ showValueWithClipboardCPButton()

showValueWithClipboardCPButton (   $valuetocopy,
  $showonlyonhover = 1,
  $texttoshow = '' 
)

Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).

Code that handle the click is inside core/js/lib_foot.js.php.

Parameters
string$valuetocopyThe value to print
int<0,1>$showonlyonhover Show the copy-paste button only on hover
string$texttoshowReplace the value to show with this text. Use 'none' to show no text (only the copy-paste picto)
Returns
string The string to print for the button

Definition at line 13104 of file functions.lib.php.

◆ startSimpleTable()

startSimpleTable (   $header,
  $link = "",
  $arguments = "",
  $emptyColumns = 0,
  $number = -1,
  $pictofulllist = '' 
)

Start a table with headers and a optional clickable number (don't forget to use "finishSimpleTable()" after the last table row)

Parameters
string$headerThe first left header of the table (automatic translated)
string$link(optional) The link to a internal dolibarr page, where to go on clicking on the number or the ... (without the first "/")
string$arguments(optional) Additional arguments for the link (e.g. "search_status=0")
integer$emptyColumns(optional) Number of empty columns to add after the first column
integer$number(optional) The number that is shown right after the first header, when -1 the link is shown as '...'
string$pictofulllist(optional) The picto to use for the full list link
Returns
void
See also
finishSimpleTable()

Definition at line 12937 of file functions.lib.php.

◆ utf8_check()

utf8_check (   $str)

Check if a string is in UTF8.

Seems similar to utf8_valid() but in pure PHP.

Parameters
string$strString to check
Returns
boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special non utf8 char or Binary)
See also
utf8_valid()

Definition at line 9943 of file functions.lib.php.

◆ utf8_valid()

utf8_valid (   $str)

Check if a string is in UTF8.

Seems similar to utf8_check().

Parameters
string$strString to check
Returns
boolean True if string is valid UTF8 string, false if corrupted
See also
utf8_check()

Definition at line 9981 of file functions.lib.php.

◆ vatrate()

vatrate (   $rate,
  $addpercent = false,
  $info_bits = 0,
  $usestarfornpr = 0,
  $html = 0 
)

Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.

Parameters
string$rateRate value to format ('19.6', '19,6', '19.6', '19,6', '19.6 (CODEX)', ...)
boolean$addpercentAdd a percent % sign in output
int$info_bitsMiscellaneous information on vat (0=Default, 1=French NPR vat)
int$usestarfornpr-1=Never show, 0 or 1=Use '*' for NPR vat rates
int$htmlUsed for html output
Returns
string String with formatted amounts ('19,6' or '19,6' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')

Definition at line 6456 of file functions.lib.php.

Referenced by ExpenseReportLine\insert().

◆ verifCond()

verifCond (   $strToEvaluate,
  $onlysimplestring = '1' 
)

Verify if condition in string is ok or not.

Parameters
string$strToEvaluateString with condition to check
string$onlysimplestring'0' (deprecated, do not use it anymore)=Accept all chars, '1' (most common use)=Accept only simple string with char 'a-z0-9\s^$_+-.*>&|=!?():"\',/@';', '2' (used for example for the compute property of extrafields)=Accept also '[]'
Returns
boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error

Definition at line 10133 of file functions.lib.php.

◆ yn()

yn (   $yesno,
  $case = 1,
  $color = 0 
)

Return yes or no in current language.

Parameters
string | int$yesnoValue to test (1, 'yes', 'true' or 0, 'no', 'false')
integer$case1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
int$color0=texte only, 1=Text is formatted with a color font style ('ok' or 'error'), 2=Text is formatted with 'ok' color.
Returns
string HTML string

Definition at line 7511 of file functions.lib.php.

Variable Documentation

◆ MODULE_MAPPING

const MODULE_MAPPING array( 'adherent' => 'member', 'member_type' => 'adherent_type', 'banque' => 'bank', 'contrat' => 'contract', 'entrepot' => 'stock', 'projet' => 'project', 'categorie' => 'category', 'commande' => 'order', 'expedition' => 'shipping', 'facture' => 'invoice', 'fichinter' => 'intervention', 'ficheinter' => 'intervention', 'propale' => 'propal', 'socpeople' => 'contact', 'fournisseur' => 'supplier', 'actioncomm' => 'agenda', 'product_price' => 'productprice', 'product_fournisseur_price' => 'productsupplierprice', )

This mapping defines the conversion to the current internal names from the alternative allowed names (including effectively deprecated and future new names (not yet used as internal names).

This allows to map any temporary or future name to the effective internal name.

The value is typically the name of module's root directory.

Definition at line 297 of file functions.lib.php.