project.class.php 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280
  1. <?php
  2. /* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2005-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2010 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  6. * Copyright (C) 2014-2017 Marcos García <marcosgdf@gmail.com>
  7. * Copyright (C) 2017 Ferran Marcet <fmarcet@2byte.es>
  8. * Copyright (C) 2019 Juanjo Menent <jmenent@2byte.es>
  9. * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
  10. *
  11. * This program is free software; you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation; either version 3 of the License, or
  14. * (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  23. */
  24. /**
  25. * \file htdocs/projet/class/project.class.php
  26. * \ingroup projet
  27. * \brief File of class to manage projects
  28. */
  29. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  30. /**
  31. * Class to manage projects
  32. */
  33. class Project extends CommonObject
  34. {
  35. /**
  36. * @var string ID to identify managed object
  37. */
  38. public $element = 'project';
  39. /**
  40. * @var string Name of table without prefix where object is stored
  41. */
  42. public $table_element = 'projet';
  43. /**
  44. * @var string Name of subtable line
  45. */
  46. public $table_element_line = 'projet_task';
  47. /**
  48. * @var string Name of field date
  49. */
  50. public $table_element_date;
  51. /**
  52. * @var string Field with ID of parent key if this field has a parent
  53. */
  54. public $fk_element = 'fk_projet';
  55. /**
  56. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  57. * @var int
  58. */
  59. public $ismultientitymanaged = 1;
  60. /**
  61. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  62. */
  63. public $picto = 'project';
  64. /**
  65. * {@inheritdoc}
  66. */
  67. protected $table_ref_field = 'ref';
  68. /**
  69. * @var string description
  70. */
  71. public $description;
  72. /**
  73. * @var string
  74. */
  75. public $title;
  76. /**
  77. * @var int Date start
  78. * @deprecated
  79. * @see $date_start
  80. */
  81. public $dateo;
  82. /**
  83. * @var int Date start
  84. */
  85. public $date_start;
  86. /**
  87. * @var int Date end
  88. * @deprecated
  89. * @see $date_end
  90. */
  91. public $datee;
  92. /**
  93. * @var int Date end
  94. */
  95. public $date_end;
  96. /**
  97. * @var int Date close
  98. */
  99. public $date_close;
  100. public $socid; // To store id of thirdparty
  101. public $thirdparty_name; // To store name of thirdparty (defined only in some cases)
  102. public $user_author_id; //!< Id of project creator. Not defined if shared project.
  103. /**
  104. * @var int user close id
  105. */
  106. public $fk_user_close;
  107. /**
  108. * @var int user close id
  109. */
  110. public $user_close_id;
  111. public $public; //!< Tell if this is a public or private project
  112. /**
  113. * @var float budget Amount
  114. */
  115. public $budget_amount;
  116. /**
  117. * @var integer Can use projects to follow opportunities
  118. */
  119. public $usage_opportunity;
  120. /**
  121. * @var integer Can follow tasks on project and enter time spent on it
  122. */
  123. public $usage_task;
  124. /**
  125. * @var integer Use to bill task spend time
  126. */
  127. public $usage_bill_time; // Is the time spent on project must be invoiced or not
  128. /**
  129. * @var integer Event organization: Use Event Organization
  130. */
  131. public $usage_organize_event;
  132. /**
  133. * @var integer Event organization: Allow unknown people to suggest new conferences
  134. */
  135. public $accept_conference_suggestions;
  136. /**
  137. * @var integer Event organization: Allow unknown people to suggest new booth
  138. */
  139. public $accept_booth_suggestions;
  140. /**
  141. * @var float Event organization: registration price
  142. */
  143. public $price_registration;
  144. /**
  145. * @var float Event organization: booth price
  146. */
  147. public $price_booth;
  148. /**
  149. * @var float Max attendees
  150. */
  151. public $max_attendees;
  152. public $statuts_short;
  153. public $statuts_long;
  154. public $statut; // 0=draft, 1=opened, 2=closed
  155. public $opp_status; // opportunity status, into table llx_c_lead_status
  156. public $fk_opp_status; // opportunity status, into table llx_c_lead_status
  157. public $opp_percent; // opportunity probability
  158. public $email_msgid;
  159. public $oldcopy;
  160. public $weekWorkLoad; // Used to store workload details of a projet
  161. public $weekWorkLoadPerTask; // Used to store workload details of tasks of a projet
  162. /**
  163. * @var int Creation date
  164. * @deprecated
  165. * @see $date_c
  166. */
  167. public $datec;
  168. /**
  169. * @var int Creation date
  170. */
  171. public $date_c;
  172. /**
  173. * @var int Modification date
  174. * @deprecated
  175. * @see $date_m
  176. */
  177. public $datem;
  178. /**
  179. * @var int Modification date
  180. */
  181. public $date_m;
  182. /**
  183. * @var Task[]
  184. */
  185. public $lines;
  186. /**
  187. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  188. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  189. * 'label' the translation key.
  190. * 'enabled' is a condition when the field must be managed.
  191. * 'position' is the sort order of field.
  192. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  193. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  194. * 'noteditable' says if field is not editable (1 or 0)
  195. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  196. * 'index' if we want an index in database.
  197. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  198. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  199. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  200. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  201. * 'help' is a string visible as a tooltip on field
  202. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  203. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  204. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  205. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  206. *
  207. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  208. */
  209. // BEGIN MODULEBUILDER PROPERTIES
  210. /**
  211. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  212. */
  213. public $fields = array(
  214. 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  215. 'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'showoncombobox'=>1, 'position'=>15, 'searchall'=>1),
  216. 'title' =>array('type'=>'varchar(255)', 'label'=>'ProjectLabel', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>17, 'showoncombobox'=>2, 'searchall'=>1),
  217. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>3, 'notnull'=>1, 'position'=>19),
  218. 'fk_soc' =>array('type'=>'integer', 'label'=>'Thirdparty', 'enabled'=>1, 'visible'=>0, 'position'=>20),
  219. 'dateo' =>array('type'=>'date', 'label'=>'DateStart', 'enabled'=>1, 'visible'=>1, 'position'=>30),
  220. 'datee' =>array('type'=>'date', 'label'=>'DateEnd', 'enabled'=>1, 'visible'=>1, 'position'=>35),
  221. 'description' =>array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>55, 'searchall'=>1),
  222. 'public' =>array('type'=>'integer', 'label'=>'Visibility', 'enabled'=>1, 'visible'=>1, 'position'=>65),
  223. 'fk_opp_status' =>array('type'=>'integer', 'label'=>'OpportunityStatusShort', 'enabled'=>'!empty($conf->global->PROJECT_USE_OPPORTUNITIES)', 'visible'=>1, 'position'=>75),
  224. 'opp_percent' =>array('type'=>'double(5,2)', 'label'=>'OpportunityProbabilityShort', 'enabled'=>'!empty($conf->global->PROJECT_USE_OPPORTUNITIES)', 'visible'=>1, 'position'=>80),
  225. 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>85, 'searchall'=>1),
  226. 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>90, 'searchall'=>1),
  227. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPdf', 'enabled'=>1, 'visible'=>0, 'position'=>95),
  228. 'date_close' =>array('type'=>'datetime', 'label'=>'DateClosing', 'enabled'=>1, 'visible'=>0, 'position'=>105),
  229. 'fk_user_close' =>array('type'=>'integer', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>0, 'position'=>110),
  230. 'opp_amount' =>array('type'=>'double(24,8)', 'label'=>'OpportunityAmountShort', 'enabled'=>1, 'visible'=>'!empty($conf->global->PROJECT_USE_OPPORTUNITIES)', 'position'=>115),
  231. 'budget_amount' =>array('type'=>'double(24,8)', 'label'=>'Budget', 'enabled'=>1, 'visible'=>1, 'position'=>119),
  232. 'usage_bill_time' =>array('type'=>'integer', 'label'=>'UsageBillTimeShort', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
  233. 'usage_opportunity' =>array('type'=>'integer', 'label'=>'UsageOpportunity', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
  234. 'usage_task' =>array('type'=>'integer', 'label'=>'UsageTasks', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  235. 'usage_organize_event' =>array('type'=>'integer', 'label'=>'UsageOrganizeEvent', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
  236. 'accept_conference_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestConf', 'enabled'=>1, 'visible'=>-1, 'position'=>146),
  237. 'accept_booth_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>147),
  238. 'price_registration' =>array('type'=>'double(24,8)', 'label'=>'PriceOfRegistration', 'enabled'=>1, 'visible'=>-1, 'position'=>148),
  239. 'price_booth' =>array('type'=>'double(24,8)', 'label'=>'PriceOfBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>149),
  240. 'max_attendees' =>array('type'=>'integer', 'label'=>'MaxNbOfAttendees', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
  241. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreationShort', 'enabled'=>1, 'visible'=>-2, 'position'=>200),
  242. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModificationShort', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>205),
  243. 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserCreation', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>210),
  244. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModification', 'enabled'=>1, 'visible'=>0, 'position'=>215),
  245. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>0, 'position'=>220),
  246. 'email_msgid'=>array('type'=>'varchar(255)', 'label'=>'EmailMsgID', 'enabled'=>1, 'visible'=>-1, 'position'=>250, 'help'=>'EmailMsgIDWhenSourceisEmail'),
  247. 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500)
  248. );
  249. // END MODULEBUILDER PROPERTIES
  250. /**
  251. * Draft status
  252. */
  253. const STATUS_DRAFT = 0;
  254. /**
  255. * Open/Validated status
  256. */
  257. const STATUS_VALIDATED = 1;
  258. /**
  259. * Closed status
  260. */
  261. const STATUS_CLOSED = 2;
  262. /**
  263. * Constructor
  264. *
  265. * @param DoliDB $db Database handler
  266. */
  267. public function __construct($db)
  268. {
  269. global $conf;
  270. $this->db = $db;
  271. $this->statuts_short = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
  272. $this->statuts_long = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
  273. global $conf;
  274. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
  275. $this->fields['rowid']['visible'] = 0;
  276. }
  277. if (empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
  278. $this->fields['fk_opp_status']['enabled'] = 0;
  279. $this->fields['opp_percent']['enabled'] = 0;
  280. $this->fields['opp_amount']['enabled'] = 0;
  281. $this->fields['usage_opportunity']['enabled'] = 0;
  282. }
  283. if (!empty($conf->global->PROJECT_HIDE_TASKS)) {
  284. $this->fields['usage_bill_time']['visible'] = 0;
  285. $this->fields['usage_task']['visible'] = 0;
  286. }
  287. if (empty($conf->eventorganization->enabled)) {
  288. $this->fields['usage_organize_event']['visible'] = 0;
  289. $this->fields['accept_conference_suggestions']['enabled'] = 0;
  290. $this->fields['accept_booth_suggestions']['enabled'] = 0;
  291. $this->fields['price_registration']['enabled'] = 0;
  292. $this->fields['price_booth']['enabled'] = 0;
  293. }
  294. }
  295. /**
  296. * Create a project into database
  297. *
  298. * @param User $user User making creation
  299. * @param int $notrigger Disable triggers
  300. * @return int <0 if KO, id of created project if OK
  301. */
  302. public function create($user, $notrigger = 0)
  303. {
  304. global $conf, $langs;
  305. $error = 0;
  306. $ret = 0;
  307. $now = dol_now();
  308. // Clean parameters
  309. $this->note_private = dol_substr($this->note_private, 0, 65535);
  310. $this->note_public = dol_substr($this->note_public, 0, 65535);
  311. // Check parameters
  312. if (!trim($this->ref)) {
  313. $this->error = 'ErrorFieldsRequired';
  314. dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
  315. return -1;
  316. }
  317. if (!empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) && !($this->socid > 0)) {
  318. $this->error = 'ErrorFieldsRequired';
  319. dol_syslog(get_class($this)."::create error -1 thirdparty not defined and option PROJECT_THIRDPARTY_REQUIRED is set", LOG_ERR);
  320. return -1;
  321. }
  322. // Create project
  323. $this->db->begin();
  324. $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet (";
  325. $sql .= "ref";
  326. $sql .= ", title";
  327. $sql .= ", description";
  328. $sql .= ", fk_soc";
  329. $sql .= ", fk_user_creat";
  330. $sql .= ", fk_statut";
  331. $sql .= ", fk_opp_status";
  332. $sql .= ", opp_percent";
  333. $sql .= ", public";
  334. $sql .= ", datec";
  335. $sql .= ", dateo";
  336. $sql .= ", datee";
  337. $sql .= ", opp_amount";
  338. $sql .= ", budget_amount";
  339. $sql .= ", usage_opportunity";
  340. $sql .= ", usage_task";
  341. $sql .= ", usage_bill_time";
  342. $sql .= ", usage_organize_event";
  343. $sql .= ", accept_conference_suggestions";
  344. $sql .= ", accept_booth_suggestions";
  345. $sql .= ", price_registration";
  346. $sql .= ", price_booth";
  347. $sql .= ", max_attendees";
  348. $sql .= ", email_msgid";
  349. $sql .= ", note_private";
  350. $sql .= ", note_public";
  351. $sql .= ", entity";
  352. $sql .= ") VALUES (";
  353. $sql .= "'".$this->db->escape($this->ref)."'";
  354. $sql .= ", '".$this->db->escape($this->title)."'";
  355. $sql .= ", '".$this->db->escape($this->description)."'";
  356. $sql .= ", ".($this->socid > 0 ? $this->socid : "null");
  357. $sql .= ", ".((int) $user->id);
  358. $sql .= ", ".(is_numeric($this->statut) ? ((int) $this->statut) : '0');
  359. $sql .= ", ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? ((int) $this->opp_status) : 'NULL');
  360. $sql .= ", ".(is_numeric($this->opp_percent) ? ((int) $this->opp_percent) : 'NULL');
  361. $sql .= ", ".($this->public ? 1 : 0);
  362. $sql .= ", '".$this->db->idate($now)."'";
  363. $sql .= ", ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
  364. $sql .= ", ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
  365. $sql .= ", ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : 'null');
  366. $sql .= ", ".(strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : 'null');
  367. $sql .= ", ".($this->usage_opportunity ? 1 : 0);
  368. $sql .= ", ".($this->usage_task ? 1 : 0);
  369. $sql .= ", ".($this->usage_bill_time ? 1 : 0);
  370. $sql .= ", ".($this->usage_organize_event ? 1 : 0);
  371. $sql .= ", ".($this->accept_conference_suggestions ? 1 : 0);
  372. $sql .= ", ".($this->accept_booth_suggestions ? 1 : 0);
  373. $sql .= ", ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : 'null');
  374. $sql .= ", ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : 'null');
  375. $sql .= ", ".(strcmp($this->max_attendees, '') ? ((int) $this->max_attendees) : 'null');
  376. $sql .= ", ".($this->email_msgid ? "'".$this->db->escape($this->email_msgid)."'" : 'null');
  377. $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : 'null');
  378. $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : 'null');
  379. $sql .= ", ".((int) $conf->entity);
  380. $sql .= ")";
  381. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  382. $resql = $this->db->query($sql);
  383. if ($resql) {
  384. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet");
  385. $ret = $this->id;
  386. if (!$notrigger) {
  387. // Call trigger
  388. $result = $this->call_trigger('PROJECT_CREATE', $user);
  389. if ($result < 0) {
  390. $error++;
  391. }
  392. // End call triggers
  393. }
  394. } else {
  395. $this->error = $this->db->lasterror();
  396. $this->errno = $this->db->lasterrno();
  397. $error++;
  398. }
  399. // Update extrafield
  400. if (!$error) {
  401. $result = $this->insertExtraFields();
  402. if ($result < 0) {
  403. $error++;
  404. }
  405. }
  406. if (!$error && !empty($conf->global->MAIN_DISABLEDRAFTSTATUS)) {
  407. $res = $this->setValid($user);
  408. if ($res < 0) {
  409. $error++;
  410. }
  411. }
  412. if (!$error) {
  413. $this->db->commit();
  414. return $ret;
  415. } else {
  416. $this->db->rollback();
  417. return -1;
  418. }
  419. }
  420. /**
  421. * Update a project
  422. *
  423. * @param User $user User object of making update
  424. * @param int $notrigger 1=Disable all triggers
  425. * @return int <=0 if KO, >0 if OK
  426. */
  427. public function update($user, $notrigger = 0)
  428. {
  429. global $langs, $conf;
  430. $error = 0;
  431. // Clean parameters
  432. $this->title = trim($this->title);
  433. $this->description = trim($this->description);
  434. if ($this->opp_amount < 0) {
  435. $this->opp_amount = '';
  436. }
  437. if ($this->opp_percent < 0) {
  438. $this->opp_percent = '';
  439. }
  440. if ($this->date_end && $this->date_end < $this->date_start) {
  441. $this->error = $langs->trans("ErrorDateEndLowerThanDateStart");
  442. $this->errors[] = $this->error;
  443. $this->db->rollback();
  444. dol_syslog(get_class($this)."::update error -3 ".$this->error, LOG_ERR);
  445. return -3;
  446. }
  447. $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
  448. if (dol_strlen(trim($this->ref)) > 0) {
  449. $this->db->begin();
  450. $sql = "UPDATE ".MAIN_DB_PREFIX."projet SET";
  451. $sql .= " ref='".$this->db->escape($this->ref)."'";
  452. $sql .= ", title = '".$this->db->escape($this->title)."'";
  453. $sql .= ", description = '".$this->db->escape($this->description)."'";
  454. $sql .= ", fk_soc = ".($this->socid > 0 ? $this->socid : "null");
  455. $sql .= ", fk_statut = ".((int) $this->statut);
  456. $sql .= ", fk_opp_status = ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? $this->opp_status : 'null');
  457. $sql .= ", opp_percent = ".((is_numeric($this->opp_percent) && $this->opp_percent != '') ? $this->opp_percent : 'null');
  458. $sql .= ", public = ".($this->public ? 1 : 0);
  459. $sql .= ", datec=".($this->date_c != '' ? "'".$this->db->idate($this->date_c)."'" : 'null');
  460. $sql .= ", dateo=".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
  461. $sql .= ", datee=".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
  462. $sql .= ", date_close=".($this->date_close != '' ? "'".$this->db->idate($this->date_close)."'" : 'null');
  463. $sql .= ", fk_user_close=".($this->fk_user_close > 0 ? $this->fk_user_close : "null");
  464. $sql .= ", opp_amount = ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : "null");
  465. $sql .= ", budget_amount = ".(strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : "null");
  466. $sql .= ", fk_user_modif = ".$user->id;
  467. $sql .= ", usage_opportunity = ".($this->usage_opportunity ? 1 : 0);
  468. $sql .= ", usage_task = ".($this->usage_task ? 1 : 0);
  469. $sql .= ", usage_bill_time = ".($this->usage_bill_time ? 1 : 0);
  470. $sql .= ", usage_organize_event = ".($this->usage_organize_event ? 1 : 0);
  471. $sql .= ", accept_conference_suggestions = ".($this->accept_conference_suggestions ? 1 : 0);
  472. $sql .= ", accept_booth_suggestions = ".($this->accept_booth_suggestions ? 1 : 0);
  473. $sql .= ", price_registration = ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : "null");
  474. $sql .= ", price_booth = ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : "null");
  475. $sql .= ", max_attendees = ".(strcmp($this->max_attendees, '') ? price2num($this->max_attendees) : "null");
  476. $sql .= ", entity = ".((int) $this->entity);
  477. $sql .= " WHERE rowid = ".((int) $this->id);
  478. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  479. $resql = $this->db->query($sql);
  480. if ($resql) {
  481. // Update extrafield
  482. if (!$error) {
  483. $result = $this->insertExtraFields();
  484. if ($result < 0) {
  485. $error++;
  486. }
  487. }
  488. if (!$error && !$notrigger) {
  489. // Call trigger
  490. $result = $this->call_trigger('PROJECT_MODIFY', $user);
  491. if ($result < 0) {
  492. $error++;
  493. }
  494. // End call triggers
  495. }
  496. if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
  497. // We remove directory
  498. if ($conf->project->dir_output) {
  499. $olddir = $conf->project->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
  500. $newdir = $conf->project->dir_output."/".dol_sanitizeFileName($this->ref);
  501. if (file_exists($olddir)) {
  502. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  503. $res = @rename($olddir, $newdir);
  504. if (!$res) {
  505. $langs->load("errors");
  506. $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
  507. $error++;
  508. }
  509. }
  510. }
  511. }
  512. if (!$error) {
  513. $this->db->commit();
  514. $result = 1;
  515. } else {
  516. $this->db->rollback();
  517. $result = -1;
  518. }
  519. } else {
  520. $this->error = $this->db->lasterror();
  521. $this->errors[] = $this->error;
  522. $this->db->rollback();
  523. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  524. $result = -4;
  525. } else {
  526. $result = -2;
  527. }
  528. dol_syslog(get_class($this)."::update error ".$result." ".$this->error, LOG_ERR);
  529. }
  530. } else {
  531. dol_syslog(get_class($this)."::update ref null");
  532. $result = -1;
  533. }
  534. return $result;
  535. }
  536. /**
  537. * Get object from database
  538. *
  539. * @param int $id Id of object to load
  540. * @param string $ref Ref of project
  541. * @param string $ref_ext Ref ext of project
  542. * @param string $email_msgid Email msgid
  543. * @return int >0 if OK, 0 if not found, <0 if KO
  544. */
  545. public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '')
  546. {
  547. global $conf;
  548. if (empty($id) && empty($ref) && empty($ref_ext) && empty($email_msgid)) {
  549. dol_syslog(get_class($this)."::fetch Bad parameters", LOG_WARNING);
  550. return -1;
  551. }
  552. $sql = "SELECT rowid, entity, ref, title, description, public, datec, opp_amount, budget_amount,";
  553. $sql .= " tms, dateo, datee, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut as status, fk_opp_status, opp_percent,";
  554. $sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid,";
  555. $sql .= " accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth, max_attendees";
  556. $sql .= " FROM ".MAIN_DB_PREFIX."projet";
  557. if (!empty($id)) {
  558. $sql .= " WHERE rowid = ".((int) $id);
  559. } else {
  560. $sql .= " WHERE entity IN (".getEntity('project').")";
  561. if (!empty($ref)) {
  562. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  563. } elseif (!empty($ref_ext)) {
  564. $sql .= " AND ref_ext = '".$this->db->escape($ref_ext)."'";
  565. } else {
  566. $sql .= " AND email_msgid = '".$this->db->escape($email_msgid)."'";
  567. }
  568. }
  569. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  570. $resql = $this->db->query($sql);
  571. if ($resql) {
  572. $num_rows = $this->db->num_rows($resql);
  573. if ($num_rows) {
  574. $obj = $this->db->fetch_object($resql);
  575. $this->id = $obj->rowid;
  576. $this->entity = $obj->entity;
  577. $this->ref = $obj->ref;
  578. $this->title = $obj->title;
  579. $this->description = $obj->description;
  580. $this->date_c = $this->db->jdate($obj->datec);
  581. $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
  582. $this->date_m = $this->db->jdate($obj->tms);
  583. $this->datem = $this->db->jdate($obj->tms); // TODO deprecated
  584. $this->date_start = $this->db->jdate($obj->dateo);
  585. $this->date_end = $this->db->jdate($obj->datee);
  586. $this->date_close = $this->db->jdate($obj->date_close);
  587. $this->note_private = $obj->note_private;
  588. $this->note_public = $obj->note_public;
  589. $this->socid = $obj->fk_soc;
  590. $this->user_author_id = $obj->fk_user_creat;
  591. $this->user_modification_id = $obj->fk_user_modif;
  592. $this->user_close_id = $obj->fk_user_close;
  593. $this->public = $obj->public;
  594. $this->statut = $obj->status; // deprecated
  595. $this->status = $obj->status;
  596. $this->opp_status = $obj->fk_opp_status;
  597. $this->opp_amount = $obj->opp_amount;
  598. $this->opp_percent = $obj->opp_percent;
  599. $this->budget_amount = $obj->budget_amount;
  600. $this->model_pdf = $obj->model_pdf;
  601. $this->modelpdf = $obj->model_pdf; // deprecated
  602. $this->usage_opportunity = (int) $obj->usage_opportunity;
  603. $this->usage_task = (int) $obj->usage_task;
  604. $this->usage_bill_time = (int) $obj->usage_bill_time;
  605. $this->usage_organize_event = (int) $obj->usage_organize_event;
  606. $this->accept_conference_suggestions = (int) $obj->accept_conference_suggestions;
  607. $this->accept_booth_suggestions = (int) $obj->accept_booth_suggestions;
  608. $this->price_registration = $obj->price_registration;
  609. $this->price_booth = $obj->price_booth;
  610. $this->max_attendees = $obj->max_attendees;
  611. $this->email_msgid = $obj->email_msgid;
  612. $this->db->free($resql);
  613. // Retrieve all extrafield
  614. // fetch optionals attributes and labels
  615. $this->fetch_optionals();
  616. return 1;
  617. }
  618. $this->db->free($resql);
  619. return 0;
  620. } else {
  621. $this->error = $this->db->lasterror();
  622. $this->errors[] = $this->db->lasterror();
  623. return -1;
  624. }
  625. }
  626. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  627. /**
  628. * Return list of elements for type, linked to a project
  629. *
  630. * @param string $type 'propal','order','invoice','order_supplier','invoice_supplier',...
  631. * @param string $tablename name of table associated of the type
  632. * @param string $datefieldname name of date field for filter
  633. * @param int $date_start Start date
  634. * @param int $date_end End date
  635. * @param string $projectkey Equivalent key to fk_projet for actual type
  636. * @return mixed Array list of object ids linked to project, < 0 or string if error
  637. */
  638. public function get_element_list($type, $tablename, $datefieldname = '', $date_start = '', $date_end = '', $projectkey = 'fk_projet')
  639. {
  640. // phpcs:enable
  641. global $hookmanager;
  642. $elements = array();
  643. if ($this->id <= 0) {
  644. return $elements;
  645. }
  646. $ids = $this->id;
  647. if ($type == 'agenda') {
  648. $sql = "SELECT id as rowid FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity('agenda').")";
  649. } elseif ($type == 'expensereport') {
  650. $sql = "SELECT ed.rowid FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."expensereport_det as ed WHERE e.rowid = ed.fk_expensereport AND e.entity IN (".getEntity('expensereport').") AND ed.fk_projet IN (".$this->db->sanitize($ids).")";
  651. } elseif ($type == 'project_task') {
  652. $sql = "SELECT DISTINCT pt.rowid FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet IN (".$this->db->sanitize($ids).")";
  653. } elseif ($type == 'project_task_time') { // Case we want to duplicate line foreach user
  654. $sql = "SELECT DISTINCT pt.rowid, ptt.fk_user FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet_task_time as ptt WHERE pt.rowid = ptt.fk_task AND pt.fk_projet IN (".$this->db->sanitize($ids).")";
  655. } elseif ($type == 'stock_mouvement') {
  656. $sql = "SELECT ms.rowid, ms.fk_user_author as fk_user FROM ".MAIN_DB_PREFIX."stock_mouvement as ms, ".MAIN_DB_PREFIX."entrepot as e WHERE e.rowid = ms.fk_entrepot AND e.entity IN (".getEntity('stock').") AND ms.origintype = 'project' AND ms.fk_origin IN (".$this->db->sanitize($ids).") AND ms.type_mouvement = 1";
  657. } elseif ($type == 'loan') {
  658. $sql = "SELECT l.rowid, l.fk_user_author as fk_user FROM ".MAIN_DB_PREFIX."loan as l WHERE l.entity IN (".getEntity('loan').") AND l.fk_projet IN (".$this->db->sanitize($ids).")";
  659. } else {
  660. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity($type).")";
  661. }
  662. if ($date_start > 0 && $type == 'loan') {
  663. $sql .= " AND (dateend > '".$this->db->idate($date_start)."' OR dateend IS NULL)";
  664. } elseif ($date_start > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
  665. if (empty($datefieldname) && !empty($this->table_element_date)) {
  666. $datefieldname = $this->table_element_date;
  667. }
  668. if (empty($datefieldname)) {
  669. return 'Error this object has no date field defined';
  670. }
  671. $sql .= " AND (".$datefieldname." >= '".$this->db->idate($date_start)."' OR ".$datefieldname." IS NULL)";
  672. }
  673. if ($date_end > 0 && $type == 'loan') {
  674. $sql .= " AND (datestart < '".$this->db->idate($date_end)."' OR datestart IS NULL)";
  675. } elseif ($date_end > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
  676. if (empty($datefieldname) && !empty($this->table_element_date)) {
  677. $datefieldname = $this->table_element_date;
  678. }
  679. if (empty($datefieldname)) {
  680. return 'Error this object has no date field defined';
  681. }
  682. $sql .= " AND (".$datefieldname." <= '".$this->db->idate($date_end)."' OR ".$datefieldname." IS NULL)";
  683. }
  684. $parameters = array(
  685. 'sql'=>$sql,
  686. 'type' => $type,
  687. 'tablename' => $tablename,
  688. 'datefieldname' => $datefieldname,
  689. 'dates' => $date_start,
  690. 'datee' => $date_end,
  691. 'fk_projet' => $projectkey,
  692. 'ids' => $ids,
  693. );
  694. $reshook = $hookmanager->executeHooks('getElementList', $parameters);
  695. if ($reshook > 0) {
  696. $sql = $hookmanager->resPrint;
  697. } else {
  698. $sql .= $hookmanager->resPrint;
  699. }
  700. if (!$sql) {
  701. return -1;
  702. }
  703. //print $sql;
  704. dol_syslog(get_class($this)."::get_element_list", LOG_DEBUG);
  705. $result = $this->db->query($sql);
  706. if ($result) {
  707. $nump = $this->db->num_rows($result);
  708. if ($nump) {
  709. $i = 0;
  710. while ($i < $nump) {
  711. $obj = $this->db->fetch_object($result);
  712. $elements[$i] = $obj->rowid.(empty($obj->fk_user) ? '' : '_'.$obj->fk_user);
  713. $i++;
  714. }
  715. $this->db->free($result);
  716. }
  717. /* Return array even if empty*/
  718. return $elements;
  719. } else {
  720. dol_print_error($this->db);
  721. }
  722. }
  723. /**
  724. * Delete a project from database
  725. *
  726. * @param User $user User
  727. * @param int $notrigger Disable triggers
  728. * @return int <0 if KO, 0 if not possible, >0 if OK
  729. */
  730. public function delete($user, $notrigger = 0)
  731. {
  732. global $langs, $conf;
  733. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  734. $error = 0;
  735. $this->db->begin();
  736. if (!$error) {
  737. // Delete linked contacts
  738. $res = $this->delete_linked_contact();
  739. if ($res < 0) {
  740. $this->error = 'ErrorFailToDeleteLinkedContact';
  741. //$error++;
  742. $this->db->rollback();
  743. return 0;
  744. }
  745. }
  746. // Set fk_projet into elements to null
  747. $listoftables = array(
  748. 'propal'=>'fk_projet', 'commande'=>'fk_projet', 'facture'=>'fk_projet',
  749. 'supplier_proposal'=>'fk_projet', 'commande_fournisseur'=>'fk_projet', 'facture_fourn'=>'fk_projet',
  750. 'expensereport_det'=>'fk_projet', 'contrat'=>'fk_projet',
  751. 'fichinter'=>'fk_projet',
  752. 'don'=>array('field'=>'fk_projet', 'module'=>'don'),
  753. 'actioncomm'=>'fk_project',
  754. 'mrp_mo'=>'fk_project',
  755. 'entrepot'=>'fk_project'
  756. );
  757. foreach ($listoftables as $key => $value) {
  758. if (is_array($value)) {
  759. if (!isModEnabled($value['module'])) {
  760. continue;
  761. }
  762. $fieldname = $value['field'];
  763. } else {
  764. $fieldname = $value;
  765. }
  766. $sql = "UPDATE ".MAIN_DB_PREFIX.$key." SET ".$fieldname." = NULL where ".$fieldname." = ".((int) $this->id);
  767. $resql = $this->db->query($sql);
  768. if (!$resql) {
  769. $this->errors[] = $this->db->lasterror();
  770. $error++;
  771. break;
  772. }
  773. }
  774. // Remove linked categories.
  775. if (!$error) {
  776. $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_project";
  777. $sql .= " WHERE fk_project = ".((int) $this->id);
  778. $result = $this->db->query($sql);
  779. if (!$result) {
  780. $error++;
  781. $this->errors[] = $this->db->lasterror();
  782. }
  783. }
  784. // Fetch tasks
  785. $this->getLinesArray($user);
  786. // Delete tasks
  787. $ret = $this->deleteTasks($user);
  788. if ($ret < 0) {
  789. $error++;
  790. }
  791. // Delete all child tables
  792. if (!$error) {
  793. $elements = array('categorie_project'); // elements to delete. TODO Make goodway to delete
  794. foreach ($elements as $table) {
  795. if (!$error) {
  796. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
  797. $sql .= " WHERE fk_project = ".((int) $this->id);
  798. $result = $this->db->query($sql);
  799. if (!$result) {
  800. $error++;
  801. $this->errors[] = $this->db->lasterror();
  802. }
  803. }
  804. }
  805. }
  806. if (!$error) {
  807. $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_extrafields";
  808. $sql .= " WHERE fk_object = ".((int) $this->id);
  809. $resql = $this->db->query($sql);
  810. if (!$resql) {
  811. $this->errors[] = $this->db->lasterror();
  812. $error++;
  813. }
  814. }
  815. // Delete project
  816. if (!$error) {
  817. $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet";
  818. $sql .= " WHERE rowid=".((int) $this->id);
  819. $resql = $this->db->query($sql);
  820. if (!$resql) {
  821. $this->errors[] = $langs->trans("CantRemoveProject", $langs->transnoentitiesnoconv("ProjectOverview"));
  822. $error++;
  823. }
  824. }
  825. if (empty($error)) {
  826. // We remove directory
  827. $projectref = dol_sanitizeFileName($this->ref);
  828. if ($conf->project->dir_output) {
  829. $dir = $conf->project->dir_output."/".$projectref;
  830. if (file_exists($dir)) {
  831. $res = @dol_delete_dir_recursive($dir);
  832. if (!$res) {
  833. $this->errors[] = 'ErrorFailToDeleteDir';
  834. $error++;
  835. }
  836. }
  837. }
  838. if (!$notrigger) {
  839. // Call trigger
  840. $result = $this->call_trigger('PROJECT_DELETE', $user);
  841. if ($result < 0) {
  842. $error++;
  843. }
  844. // End call triggers
  845. }
  846. }
  847. if (empty($error)) {
  848. $this->db->commit();
  849. return 1;
  850. } else {
  851. foreach ($this->errors as $errmsg) {
  852. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  853. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  854. }
  855. dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
  856. $this->db->rollback();
  857. return -1;
  858. }
  859. }
  860. /**
  861. * Return the count of a type of linked elements of this project
  862. *
  863. * @param string $type The type of the linked elements (e.g. 'propal', 'order', 'invoice', 'order_supplier', 'invoice_supplier')
  864. * @param string $tablename The name of table associated of the type
  865. * @param string $projectkey (optional) Equivalent key to fk_projet for actual type
  866. * @return integer The count of the linked elements (the count is zero on request error too)
  867. */
  868. public function getElementCount($type, $tablename, $projectkey = 'fk_projet')
  869. {
  870. if ($this->id <= 0) {
  871. return 0;
  872. }
  873. if ($type == 'agenda') {
  874. $sql = "SELECT COUNT(id) as nb FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project = ".((int) $this->id)." AND entity IN (".getEntity('agenda').")";
  875. } elseif ($type == 'expensereport') {
  876. $sql = "SELECT COUNT(ed.rowid) as nb FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."expensereport_det as ed WHERE e.rowid = ed.fk_expensereport AND e.entity IN (".getEntity('expensereport').") AND ed.fk_projet = ".((int) $this->id);
  877. } elseif ($type == 'project_task') {
  878. $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet = ".((int) $this->id);
  879. } elseif ($type == 'project_task_time') { // Case we want to duplicate line foreach user
  880. $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet_task_time as ptt WHERE pt.rowid = ptt.fk_task AND pt.fk_projet = ".((int) $this->id);
  881. } elseif ($type == 'stock_mouvement') {
  882. $sql = "SELECT COUNT(ms.rowid) as nb FROM ".MAIN_DB_PREFIX."stock_mouvement as ms, ".MAIN_DB_PREFIX."entrepot as e WHERE e.rowid = ms.fk_entrepot AND e.entity IN (".getEntity('stock').") AND ms.origintype = 'project' AND ms.fk_origin = ".((int) $this->id)." AND ms.type_mouvement = 1";
  883. } elseif ($type == 'loan') {
  884. $sql = "SELECT COUNT(l.rowid) as nb FROM ".MAIN_DB_PREFIX."loan as l WHERE l.entity IN (".getEntity('loan').") AND l.fk_projet = ".((int) $this->id);
  885. } else {
  886. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." = ".((int) $this->id)." AND entity IN (".getEntity($type).")";
  887. }
  888. $result = $this->db->query($sql);
  889. if (!$result) {
  890. return 0;
  891. }
  892. $obj = $this->db->fetch_object($result);
  893. $this->db->free($result);
  894. return $obj->nb;
  895. }
  896. /**
  897. * Delete tasks with no children first, then task with children recursively
  898. *
  899. * @param User $user User
  900. * @return int <0 if KO, 1 if OK
  901. */
  902. public function deleteTasks($user)
  903. {
  904. $countTasks = count($this->lines);
  905. $deleted = false;
  906. if ($countTasks) {
  907. foreach ($this->lines as $task) {
  908. if ($task->hasChildren() <= 0) { // If there is no children (or error to detect them)
  909. $deleted = true;
  910. $ret = $task->delete($user);
  911. if ($ret <= 0) {
  912. $this->errors[] = $this->db->lasterror();
  913. return -1;
  914. }
  915. }
  916. }
  917. }
  918. $this->getLinesArray($user);
  919. if ($deleted && count($this->lines) < $countTasks) {
  920. if (count($this->lines)) {
  921. $this->deleteTasks($this->lines);
  922. }
  923. }
  924. return 1;
  925. }
  926. /**
  927. * Validate a project
  928. *
  929. * @param User $user User that validate
  930. * @param int $notrigger 1=Disable triggers
  931. * @return int <0 if KO, >0 if OK
  932. */
  933. public function setValid($user, $notrigger = 0)
  934. {
  935. global $langs, $conf;
  936. $error = 0;
  937. if ($this->statut != 1) {
  938. // Check parameters
  939. if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->title)) {
  940. $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("Label")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
  941. return -1;
  942. }
  943. $this->db->begin();
  944. $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
  945. $sql .= " SET fk_statut = 1";
  946. $sql .= " WHERE rowid = ".((int) $this->id);
  947. $sql .= " AND entity = ".((int) $conf->entity);
  948. dol_syslog(get_class($this)."::setValid", LOG_DEBUG);
  949. $resql = $this->db->query($sql);
  950. if ($resql) {
  951. // Call trigger
  952. if (empty($notrigger)) {
  953. $result = $this->call_trigger('PROJECT_VALIDATE', $user);
  954. if ($result < 0) {
  955. $error++;
  956. }
  957. // End call triggers
  958. }
  959. if (!$error) {
  960. $this->statut = 1;
  961. $this->db->commit();
  962. return 1;
  963. } else {
  964. $this->db->rollback();
  965. $this->error = join(',', $this->errors);
  966. dol_syslog(get_class($this)."::setValid ".$this->error, LOG_ERR);
  967. return -1;
  968. }
  969. } else {
  970. $this->db->rollback();
  971. $this->error = $this->db->lasterror();
  972. return -1;
  973. }
  974. }
  975. }
  976. /**
  977. * Close a project
  978. *
  979. * @param User $user User that close project
  980. * @return int <0 if KO, 0 if already closed, >0 if OK
  981. */
  982. public function setClose($user)
  983. {
  984. global $langs, $conf;
  985. $now = dol_now();
  986. $error = 0;
  987. if ($this->statut != self::STATUS_CLOSED) {
  988. $this->db->begin();
  989. $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
  990. $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", fk_user_close = ".((int) $user->id).", date_close = '".$this->db->idate($now)."'";
  991. $sql .= " WHERE rowid = ".((int) $this->id);
  992. $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
  993. if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
  994. // TODO What to do if fk_opp_status is not code 'WON' or 'LOST'
  995. }
  996. dol_syslog(get_class($this)."::setClose", LOG_DEBUG);
  997. $resql = $this->db->query($sql);
  998. if ($resql) {
  999. // Call trigger
  1000. $result = $this->call_trigger('PROJECT_CLOSE', $user);
  1001. if ($result < 0) {
  1002. $error++;
  1003. }
  1004. // End call triggers
  1005. if (!$error) {
  1006. $this->statut = 2;
  1007. $this->db->commit();
  1008. return 1;
  1009. } else {
  1010. $this->db->rollback();
  1011. $this->error = join(',', $this->errors);
  1012. dol_syslog(get_class($this)."::setClose ".$this->error, LOG_ERR);
  1013. return -1;
  1014. }
  1015. } else {
  1016. $this->db->rollback();
  1017. $this->error = $this->db->lasterror();
  1018. return -1;
  1019. }
  1020. }
  1021. return 0;
  1022. }
  1023. /**
  1024. * Return status label of object
  1025. *
  1026. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  1027. * @return string Label
  1028. */
  1029. public function getLibStatut($mode = 0)
  1030. {
  1031. return $this->LibStatut(isset($this->statut) ? $this->statut : $this->status, $mode);
  1032. }
  1033. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1034. /**
  1035. * Renvoi status label for a status
  1036. *
  1037. * @param int $status id status
  1038. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1039. * @return string Label
  1040. */
  1041. public function LibStatut($status, $mode = 0)
  1042. {
  1043. // phpcs:enable
  1044. global $langs;
  1045. $statustrans = array(
  1046. 0 => 'status0',
  1047. 1 => 'status4',
  1048. 2 => 'status6',
  1049. );
  1050. $statusClass = 'status0';
  1051. if (!empty($statustrans[$status])) {
  1052. $statusClass = $statustrans[$status];
  1053. }
  1054. return dolGetStatus($langs->transnoentitiesnoconv($this->statuts_long[$status]), $langs->transnoentitiesnoconv($this->statuts_short[$status]), '', $statusClass, $mode);
  1055. }
  1056. /**
  1057. * Return clickable name (with picto eventually)
  1058. *
  1059. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1060. * @param string $option Variant where the link point to ('', 'nolink')
  1061. * @param int $addlabel 0=Default, 1=Add label into string, >1=Add first chars into string
  1062. * @param string $moreinpopup Text to add into popup
  1063. * @param string $sep Separator between ref and label if option addlabel is set
  1064. * @param int $notooltip 1=Disable tooltip
  1065. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1066. * @param string $morecss More css on a link
  1067. * @return string String with URL
  1068. */
  1069. public function getNomUrl($withpicto = 0, $option = '', $addlabel = 0, $moreinpopup = '', $sep = ' - ', $notooltip = 0, $save_lastsearch_value = -1, $morecss = '')
  1070. {
  1071. global $conf, $langs, $user, $hookmanager;
  1072. if (!empty($conf->dol_no_mouse_hover)) {
  1073. $notooltip = 1; // Force disable tooltips
  1074. }
  1075. $result = '';
  1076. if (!empty($conf->global->PROJECT_OPEN_ALWAYS_ON_TAB)) {
  1077. $option = $conf->global->PROJECT_OPEN_ALWAYS_ON_TAB;
  1078. }
  1079. $label = '';
  1080. if ($option != 'nolink') {
  1081. $label = img_picto('', $this->picto, 'class="pictofixedwidth"').' <u class="paddingrightonly">'.$langs->trans("Project").'</u>';
  1082. }
  1083. if (isset($this->status)) {
  1084. $label .= ' '.$this->getLibStatut(5);
  1085. }
  1086. $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('Ref').': </b>'.$this->ref; // The space must be after the : to not being explode when showing the title in img_picto
  1087. $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('Label').': </b>'.$this->title; // The space must be after the : to not being explode when showing the title in img_picto
  1088. if (isset($this->public)) {
  1089. $label .= '<br><b>'.$langs->trans("Visibility").":</b> ";
  1090. $label .= ($this->public ? img_picto($langs->trans('SharedProject'), 'world', 'class="paddingrightonly"').$langs->trans("SharedProject") : img_picto($langs->trans('PrivateProject'), 'private', 'class="paddingrightonly"').$langs->trans("PrivateProject"));
  1091. }
  1092. if (!empty($this->thirdparty_name)) {
  1093. $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('ThirdParty').': </b>'.$this->thirdparty_name; // The space must be after the : to not being explode when showing the title in img_picto
  1094. }
  1095. if (!empty($this->date_start)) {
  1096. $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('DateStart').': </b>'.dol_print_date($this->date_start, 'day'); // The space must be after the : to not being explode when showing the title in img_picto
  1097. }
  1098. if (!empty($this->date_end)) {
  1099. $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('DateEnd').': </b>'.dol_print_date($this->date_end, 'day'); // The space must be after the : to not being explode when showing the title in img_picto
  1100. }
  1101. if ($moreinpopup) {
  1102. $label .= '<br>'.$moreinpopup;
  1103. }
  1104. $url = '';
  1105. if ($option != 'nolink') {
  1106. if (preg_match('/\.php$/', $option)) {
  1107. $url = dol_buildpath($option, 1).'?id='.$this->id;
  1108. } elseif ($option == 'task') {
  1109. $url = DOL_URL_ROOT.'/projet/tasks.php?id='.$this->id;
  1110. } elseif ($option == 'preview') {
  1111. $url = DOL_URL_ROOT.'/projet/element.php?id='.$this->id;
  1112. } elseif ($option == 'eventorganization') {
  1113. $url = DOL_URL_ROOT.'/eventorganization/conferenceorbooth_list.php?projectid='.$this->id;
  1114. } else {
  1115. $url = DOL_URL_ROOT.'/projet/card.php?id='.$this->id;
  1116. }
  1117. // Add param to save lastsearch_values or not
  1118. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1119. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1120. $add_save_lastsearch_values = 1;
  1121. }
  1122. if ($add_save_lastsearch_values) {
  1123. $url .= '&save_lastsearch_values=1';
  1124. }
  1125. }
  1126. $linkclose = '';
  1127. if (empty($notooltip) && $user->hasRight('projet', 'lire')) {
  1128. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1129. $label = $langs->trans("ShowProject");
  1130. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1131. }
  1132. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1133. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1134. } else {
  1135. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1136. }
  1137. $picto = 'projectpub';
  1138. if (!$this->public) {
  1139. $picto = 'project';
  1140. }
  1141. $linkstart = '<a href="'.$url.'"';
  1142. $linkstart .= $linkclose.'>';
  1143. $linkend = '</a>';
  1144. $result .= $linkstart;
  1145. if ($withpicto) {
  1146. $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip pictofixedwidth em088"'), 0, 0, $notooltip ? 0 : 1);
  1147. }
  1148. if ($withpicto != 2) {
  1149. $result .= $this->ref;
  1150. }
  1151. $result .= $linkend;
  1152. if ($withpicto != 2) {
  1153. $result .= (($addlabel && $this->title) ? $sep.dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)) : '');
  1154. }
  1155. global $action;
  1156. $hookmanager->initHooks(array('projectdao'));
  1157. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1158. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1159. if ($reshook > 0) {
  1160. $result = $hookmanager->resPrint;
  1161. } else {
  1162. $result .= $hookmanager->resPrint;
  1163. }
  1164. return $result;
  1165. }
  1166. /**
  1167. * Initialise an instance with random values.
  1168. * Used to build previews or test instances.
  1169. * id must be 0 if object instance is a specimen.
  1170. *
  1171. * @return void
  1172. */
  1173. public function initAsSpecimen()
  1174. {
  1175. global $user, $langs, $conf;
  1176. $now = dol_now();
  1177. // Initialise parameters
  1178. $this->id = 0;
  1179. $this->ref = 'SPECIMEN';
  1180. $this->specimen = 1;
  1181. $this->socid = 1;
  1182. $this->date_c = $now;
  1183. $this->date_m = $now;
  1184. $this->date_start = $now;
  1185. $this->date_end = $now + (3600 * 24 * 365);
  1186. $this->note_public = 'SPECIMEN';
  1187. $this->fk_ele = 20000;
  1188. $this->opp_amount = 20000;
  1189. $this->budget_amount = 10000;
  1190. $this->usage_opportunity = 1;
  1191. $this->usage_task = 1;
  1192. $this->usage_bill_time = 1;
  1193. $this->usage_organize_event = 1;
  1194. /*
  1195. $nbp = mt_rand(1, 9);
  1196. $xnbp = 0;
  1197. while ($xnbp < $nbp)
  1198. {
  1199. $line = new Task($this->db);
  1200. $line->fk_project = 0;
  1201. $line->label = $langs->trans("Label") . " " . $xnbp;
  1202. $line->description = $langs->trans("Description") . " " . $xnbp;
  1203. $this->lines[]=$line;
  1204. $xnbp++;
  1205. }
  1206. */
  1207. }
  1208. /**
  1209. * Check if user has permission on current project
  1210. *
  1211. * @param User $user Object user to evaluate
  1212. * @param string $mode Type of permission we want to know: 'read', 'write'
  1213. * @return int >0 if user has permission, <0 if user has no permission
  1214. */
  1215. public function restrictedProjectArea(User $user, $mode = 'read')
  1216. {
  1217. // To verify role of users
  1218. $userAccess = 0;
  1219. if (($mode == 'read' && !empty($user->rights->projet->all->lire)) || ($mode == 'write' && !empty($user->rights->projet->all->creer)) || ($mode == 'delete' && !empty($user->rights->projet->all->supprimer))) {
  1220. $userAccess = 1;
  1221. } elseif ($this->public && (($mode == 'read' && !empty($user->rights->projet->lire)) || ($mode == 'write' && !empty($user->rights->projet->creer)) || ($mode == 'delete' && !empty($user->rights->projet->supprimer)))) {
  1222. $userAccess = 1;
  1223. } else { // No access due to permission to read all projects, so we check if we are a contact of project
  1224. foreach (array('internal', 'external') as $source) {
  1225. $userRole = $this->liste_contact(4, $source);
  1226. $num = count($userRole);
  1227. $nblinks = 0;
  1228. while ($nblinks < $num) {
  1229. if ($source == 'internal' && $user->id == $userRole[$nblinks]['id']) { // $userRole[$nblinks]['id'] is id of user (llx_user) for internal contacts
  1230. if ($mode == 'read' && $user->rights->projet->lire) {
  1231. $userAccess++;
  1232. }
  1233. if ($mode == 'write' && $user->rights->projet->creer) {
  1234. $userAccess++;
  1235. }
  1236. if ($mode == 'delete' && $user->rights->projet->supprimer) {
  1237. $userAccess++;
  1238. }
  1239. }
  1240. if ($source == 'external' && $user->socid > 0 && $user->socid == $userRole[$nblinks]['socid']) { // $userRole[$nblinks]['id'] is id of contact (llx_socpeople) or external contacts
  1241. if ($mode == 'read' && $user->rights->projet->lire) {
  1242. $userAccess++;
  1243. }
  1244. if ($mode == 'write' && $user->rights->projet->creer) {
  1245. $userAccess++;
  1246. }
  1247. if ($mode == 'delete' && $user->rights->projet->supprimer) {
  1248. $userAccess++;
  1249. }
  1250. }
  1251. $nblinks++;
  1252. }
  1253. }
  1254. //if (empty($nblinks)) // If nobody has permission, we grant creator
  1255. //{
  1256. // if ((!empty($this->user_author_id) && $this->user_author_id == $user->id))
  1257. // {
  1258. // $userAccess = 1;
  1259. // }
  1260. //}
  1261. }
  1262. return ($userAccess ? $userAccess : -1);
  1263. }
  1264. /**
  1265. * Return array of projects a user has permission on, is affected to, or all projects
  1266. *
  1267. * @param User $user User object
  1268. * @param int $mode 0=All project I have permission on (assigned to me or public), 1=Projects assigned to me only, 2=Will return list of all projects with no test on contacts
  1269. * @param int $list 0=Return array, 1=Return string list
  1270. * @param int $socid 0=No filter on third party, id of third party
  1271. * @param string $filter additionnal filter on project (statut, ref, ...)
  1272. * @return array or string Array of projects id, or string with projects id separated with "," if list is 1
  1273. */
  1274. public function getProjectsAuthorizedForUser($user, $mode = 0, $list = 0, $socid = 0, $filter = '')
  1275. {
  1276. $projects = array();
  1277. $temp = array();
  1278. $sql = "SELECT ".(($mode == 0 || $mode == 1) ? "DISTINCT " : "")."p.rowid, p.ref";
  1279. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  1280. if ($mode == 0) {
  1281. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = p.rowid";
  1282. } elseif ($mode == 1) {
  1283. $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
  1284. } elseif ($mode == 2) {
  1285. // No filter. Use this if user has permission to see all project
  1286. }
  1287. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  1288. // Internal users must see project he is contact to even if project linked to a third party he can't see.
  1289. //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
  1290. if ($socid > 0) {
  1291. $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
  1292. }
  1293. // Get id of types of contacts for projects (This list never contains a lot of elements)
  1294. $listofprojectcontacttype = array();
  1295. $sql2 = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
  1296. $sql2 .= " WHERE ctc.element = '".$this->db->escape($this->element)."'";
  1297. $sql2 .= " AND ctc.source = 'internal'";
  1298. $resql = $this->db->query($sql2);
  1299. if ($resql) {
  1300. while ($obj = $this->db->fetch_object($resql)) {
  1301. $listofprojectcontacttype[$obj->rowid] = $obj->code;
  1302. }
  1303. } else {
  1304. dol_print_error($this->db);
  1305. }
  1306. if (count($listofprojectcontacttype) == 0) {
  1307. $listofprojectcontacttype[0] = '0'; // To avoid syntax error if not found
  1308. }
  1309. if ($mode == 0) {
  1310. $sql .= " AND ( p.public = 1";
  1311. $sql .= " OR ( ec.fk_c_type_contact IN (".$this->db->sanitize(join(',', array_keys($listofprojectcontacttype))).")";
  1312. $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
  1313. $sql .= " )";
  1314. } elseif ($mode == 1) {
  1315. $sql .= " AND ec.element_id = p.rowid";
  1316. $sql .= " AND (";
  1317. $sql .= " ( ec.fk_c_type_contact IN (".$this->db->sanitize(join(',', array_keys($listofprojectcontacttype))).")";
  1318. $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
  1319. $sql .= " )";
  1320. } elseif ($mode == 2) {
  1321. // No filter. Use this if user has permission to see all project
  1322. }
  1323. $sql .= $filter;
  1324. //print $sql;
  1325. $resql = $this->db->query($sql);
  1326. if ($resql) {
  1327. $num = $this->db->num_rows($resql);
  1328. $i = 0;
  1329. while ($i < $num) {
  1330. $row = $this->db->fetch_row($resql);
  1331. $projects[$row[0]] = $row[1];
  1332. $temp[] = $row[0];
  1333. $i++;
  1334. }
  1335. $this->db->free($resql);
  1336. if ($list) {
  1337. if (empty($temp)) {
  1338. return '0';
  1339. }
  1340. $result = implode(',', $temp);
  1341. return $result;
  1342. }
  1343. } else {
  1344. dol_print_error($this->db);
  1345. }
  1346. return $projects;
  1347. }
  1348. /**
  1349. * Load an object from its id and create a new one in database
  1350. *
  1351. * @param User $user User making the clone
  1352. * @param int $fromid Id of object to clone
  1353. * @param bool $clone_contact Clone contact of project
  1354. * @param bool $clone_task Clone task of project
  1355. * @param bool $clone_project_file Clone file of project
  1356. * @param bool $clone_task_file Clone file of task (if task are copied)
  1357. * @param bool $clone_note Clone note of project
  1358. * @param bool $move_date Move task date on clone
  1359. * @param integer $notrigger No trigger flag
  1360. * @param int $newthirdpartyid New thirdparty id
  1361. * @return int New id of clone
  1362. */
  1363. public function createFromClone(User $user, $fromid, $clone_contact = false, $clone_task = true, $clone_project_file = false, $clone_task_file = false, $clone_note = true, $move_date = true, $notrigger = 0, $newthirdpartyid = 0)
  1364. {
  1365. global $langs, $conf;
  1366. $error = 0;
  1367. dol_syslog("createFromClone clone_contact=".$clone_contact." clone_task=".$clone_task." clone_project_file=".$clone_project_file." clone_note=".$clone_note." move_date=".$move_date, LOG_DEBUG);
  1368. $now = dol_mktime(0, 0, 0, idate('m', dol_now()), idate('d', dol_now()), idate('Y', dol_now()));
  1369. $clone_project = new Project($this->db);
  1370. $clone_project->context['createfromclone'] = 'createfromclone';
  1371. $this->db->begin();
  1372. // Load source object
  1373. $clone_project->fetch($fromid);
  1374. $clone_project->fetch_optionals();
  1375. if ($newthirdpartyid > 0) {
  1376. $clone_project->socid = $newthirdpartyid;
  1377. }
  1378. $clone_project->fetch_thirdparty();
  1379. $orign_dt_start = $clone_project->date_start;
  1380. $orign_project_ref = $clone_project->ref;
  1381. $clone_project->id = 0;
  1382. if ($move_date) {
  1383. $clone_project->date_start = $now;
  1384. if (!(empty($clone_project->date_end))) {
  1385. $clone_project->date_end = $clone_project->date_end + ($now - $orign_dt_start);
  1386. }
  1387. }
  1388. $clone_project->date_c = $now;
  1389. if (!$clone_note) {
  1390. $clone_project->note_private = '';
  1391. $clone_project->note_public = '';
  1392. }
  1393. //Generate next ref
  1394. $defaultref = '';
  1395. $obj = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
  1396. // Search template files
  1397. $file = ''; $classname = ''; $filefound = 0;
  1398. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  1399. foreach ($dirmodels as $reldir) {
  1400. $file = dol_buildpath($reldir."core/modules/project/".$obj.'.php', 0);
  1401. if (file_exists($file)) {
  1402. $filefound = 1;
  1403. dol_include_once($reldir."core/modules/project/".$obj.'.php');
  1404. $modProject = new $obj;
  1405. $defaultref = $modProject->getNextValue(is_object($clone_project->thirdparty) ? $clone_project->thirdparty : null, $clone_project);
  1406. break;
  1407. }
  1408. }
  1409. if (is_numeric($defaultref) && $defaultref <= 0) {
  1410. $defaultref = '';
  1411. }
  1412. $clone_project->ref = $defaultref;
  1413. $clone_project->title = $langs->trans("CopyOf").' '.$clone_project->title;
  1414. // Create clone
  1415. $result = $clone_project->create($user, $notrigger);
  1416. // Other options
  1417. if ($result < 0) {
  1418. $this->error .= $clone_project->error;
  1419. $error++;
  1420. }
  1421. if (!$error) {
  1422. //Get the new project id
  1423. $clone_project_id = $clone_project->id;
  1424. //Note Update
  1425. if (!$clone_note) {
  1426. $clone_project->note_private = '';
  1427. $clone_project->note_public = '';
  1428. } else {
  1429. $this->db->begin();
  1430. $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES | ENT_HTML5), '_public');
  1431. if ($res < 0) {
  1432. $this->error .= $clone_project->error;
  1433. $error++;
  1434. $this->db->rollback();
  1435. } else {
  1436. $this->db->commit();
  1437. }
  1438. $this->db->begin();
  1439. $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_private, ENT_QUOTES | ENT_HTML5), '_private');
  1440. if ($res < 0) {
  1441. $this->error .= $clone_project->error;
  1442. $error++;
  1443. $this->db->rollback();
  1444. } else {
  1445. $this->db->commit();
  1446. }
  1447. }
  1448. //Duplicate contact
  1449. if ($clone_contact) {
  1450. $origin_project = new Project($this->db);
  1451. $origin_project->fetch($fromid);
  1452. foreach (array('internal', 'external') as $source) {
  1453. $tab = $origin_project->liste_contact(-1, $source);
  1454. if (is_array($tab) && count($tab)>0) {
  1455. foreach ($tab as $contacttoadd) {
  1456. $clone_project->add_contact($contacttoadd['id'], $contacttoadd['code'], $contacttoadd['source'], $notrigger);
  1457. if ($clone_project->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1458. $langs->load("errors");
  1459. $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
  1460. $error++;
  1461. } else {
  1462. if ($clone_project->error != '') {
  1463. $this->error .= $clone_project->error;
  1464. $error++;
  1465. }
  1466. }
  1467. }
  1468. } elseif ($tab < 0) {
  1469. $this->error .= $origin_project->error;
  1470. $error++;
  1471. }
  1472. }
  1473. }
  1474. //Duplicate file
  1475. if ($clone_project_file) {
  1476. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1477. $clone_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($defaultref);
  1478. $ori_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($orign_project_ref);
  1479. if (dol_mkdir($clone_project_dir) >= 0) {
  1480. $filearray = dol_dir_list($ori_project_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
  1481. foreach ($filearray as $key => $file) {
  1482. $rescopy = dol_copy($ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name'], 0, 1);
  1483. if (is_numeric($rescopy) && $rescopy < 0) {
  1484. $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name']);
  1485. $error++;
  1486. }
  1487. }
  1488. } else {
  1489. $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
  1490. $error++;
  1491. }
  1492. }
  1493. //Duplicate task
  1494. if ($clone_task) {
  1495. require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  1496. $taskstatic = new Task($this->db);
  1497. // Security check
  1498. $socid = 0;
  1499. if ($user->socid > 0) {
  1500. $socid = $user->socid;
  1501. }
  1502. $tasksarray = $taskstatic->getTasksArray(0, 0, $fromid, $socid, 0);
  1503. $tab_conv_child_parent = array();
  1504. // Loop on each task, to clone it
  1505. foreach ($tasksarray as $tasktoclone) {
  1506. $result_clone = $taskstatic->createFromClone($user, $tasktoclone->id, $clone_project_id, $tasktoclone->fk_parent, $move_date, true, false, $clone_task_file, true, false);
  1507. if ($result_clone <= 0) {
  1508. $this->error .= $taskstatic->error;
  1509. $error++;
  1510. } else {
  1511. $new_task_id = $result_clone;
  1512. $taskstatic->fetch($tasktoclone->id);
  1513. //manage new parent clone task id
  1514. // if the current task has child we store the original task id and the equivalent clone task id
  1515. if (($taskstatic->hasChildren()) && !array_key_exists($tasktoclone->id, $tab_conv_child_parent)) {
  1516. $tab_conv_child_parent[$tasktoclone->id] = $new_task_id;
  1517. }
  1518. }
  1519. }
  1520. //Parse all clone node to be sure to update new parent
  1521. $tasksarray = $taskstatic->getTasksArray(0, 0, $clone_project_id, $socid, 0);
  1522. foreach ($tasksarray as $task_cloned) {
  1523. $taskstatic->fetch($task_cloned->id);
  1524. if ($taskstatic->fk_task_parent != 0) {
  1525. $taskstatic->fk_task_parent = $tab_conv_child_parent[$taskstatic->fk_task_parent];
  1526. }
  1527. $res = $taskstatic->update($user, $notrigger);
  1528. if ($result_clone <= 0) {
  1529. $this->error .= $taskstatic->error;
  1530. $error++;
  1531. }
  1532. }
  1533. }
  1534. }
  1535. unset($clone_project->context['createfromclone']);
  1536. if (!$error) {
  1537. $this->db->commit();
  1538. return $clone_project_id;
  1539. } else {
  1540. $this->db->rollback();
  1541. dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
  1542. return -1;
  1543. }
  1544. }
  1545. /**
  1546. * Shift project task date from current date to delta
  1547. *
  1548. * @param integer $old_project_dt_start Old project start date
  1549. * @return int 1 if OK or < 0 if KO
  1550. */
  1551. public function shiftTaskDate($old_project_dt_start)
  1552. {
  1553. global $user, $langs, $conf;
  1554. $error = 0;
  1555. $result = 0;
  1556. $taskstatic = new Task($this->db);
  1557. // Security check
  1558. $socid = 0;
  1559. if ($user->socid > 0) {
  1560. $socid = $user->socid;
  1561. }
  1562. $tasksarray = $taskstatic->getTasksArray(0, 0, $this->id, $socid, 0);
  1563. foreach ($tasksarray as $tasktoshiftdate) {
  1564. $to_update = false;
  1565. // Fetch only if update of date will be made
  1566. if ((!empty($tasktoshiftdate->date_start)) || (!empty($tasktoshiftdate->date_end))) {
  1567. //dol_syslog(get_class($this)."::shiftTaskDate to_update", LOG_DEBUG);
  1568. $to_update = true;
  1569. $task = new Task($this->db);
  1570. $result = $task->fetch($tasktoshiftdate->id);
  1571. if (!$result) {
  1572. $error++;
  1573. $this->error .= $task->error;
  1574. }
  1575. }
  1576. //print "$this->date_start + $tasktoshiftdate->date_start - $old_project_dt_start";exit;
  1577. //Calcultate new task start date with difference between old proj start date and origin task start date
  1578. if (!empty($tasktoshiftdate->date_start)) {
  1579. $task->date_start = $this->date_start + ($tasktoshiftdate->date_start - $old_project_dt_start);
  1580. }
  1581. //Calcultate new task end date with difference between origin proj end date and origin task end date
  1582. if (!empty($tasktoshiftdate->date_end)) {
  1583. $task->date_end = $this->date_start + ($tasktoshiftdate->date_end - $old_project_dt_start);
  1584. }
  1585. if ($to_update) {
  1586. $result = $task->update($user);
  1587. if (!$result) {
  1588. $error++;
  1589. $this->error .= $task->error;
  1590. }
  1591. }
  1592. }
  1593. if ($error != 0) {
  1594. return -1;
  1595. }
  1596. return $result;
  1597. }
  1598. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1599. /**
  1600. * Associate element to a project
  1601. *
  1602. * @param string $tableName Table of the element to update
  1603. * @param int $elementSelectId Key-rowid of the line of the element to update
  1604. * @return int 1 if OK or < 0 if KO
  1605. */
  1606. public function update_element($tableName, $elementSelectId)
  1607. {
  1608. // phpcs:enable
  1609. $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
  1610. if ($tableName == "actioncomm") {
  1611. $sql .= " SET fk_project=".$this->id;
  1612. $sql .= " WHERE id=".((int) $elementSelectId);
  1613. } elseif ($tableName == "entrepot") {
  1614. $sql .= " SET fk_project=".$this->id;
  1615. $sql .= " WHERE rowid=".((int) $elementSelectId);
  1616. } else {
  1617. $sql .= " SET fk_projet=".$this->id;
  1618. $sql .= " WHERE rowid=".((int) $elementSelectId);
  1619. }
  1620. dol_syslog(get_class($this)."::update_element", LOG_DEBUG);
  1621. $resql = $this->db->query($sql);
  1622. if (!$resql) {
  1623. $this->error = $this->db->lasterror();
  1624. return -1;
  1625. } else {
  1626. return 1;
  1627. }
  1628. }
  1629. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1630. /**
  1631. * Associate element to a project
  1632. *
  1633. * @param string $tableName Table of the element to update
  1634. * @param int $elementSelectId Key-rowid of the line of the element to update
  1635. * @param string $projectfield The column name that stores the link with the project
  1636. *
  1637. * @return int 1 if OK or < 0 if KO
  1638. */
  1639. public function remove_element($tableName, $elementSelectId, $projectfield = 'fk_projet')
  1640. {
  1641. // phpcs:enable
  1642. $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
  1643. if ($tableName == "actioncomm") {
  1644. $sql .= " SET fk_project=NULL";
  1645. $sql .= " WHERE id=".((int) $elementSelectId);
  1646. } else {
  1647. $sql .= " SET ".$projectfield."=NULL";
  1648. $sql .= " WHERE rowid=".((int) $elementSelectId);
  1649. }
  1650. dol_syslog(get_class($this)."::remove_element", LOG_DEBUG);
  1651. $resql = $this->db->query($sql);
  1652. if (!$resql) {
  1653. $this->error = $this->db->lasterror();
  1654. return -1;
  1655. } else {
  1656. return 1;
  1657. }
  1658. }
  1659. /**
  1660. * Create an intervention document on disk using template defined into PROJECT_ADDON_PDF
  1661. *
  1662. * @param string $modele Force template to use ('' by default)
  1663. * @param Translate $outputlangs Objet lang to use for translation
  1664. * @param int $hidedetails Hide details of lines
  1665. * @param int $hidedesc Hide description
  1666. * @param int $hideref Hide ref
  1667. * @return int 0 if KO, 1 if OK
  1668. */
  1669. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  1670. {
  1671. global $conf, $langs;
  1672. $langs->load("projects");
  1673. if (!dol_strlen($modele)) {
  1674. $modele = 'baleine';
  1675. if ($this->model_pdf) {
  1676. $modele = $this->model_pdf;
  1677. } elseif (!empty($conf->global->PROJECT_ADDON_PDF)) {
  1678. $modele = $conf->global->PROJECT_ADDON_PDF;
  1679. }
  1680. }
  1681. $modelpath = "core/modules/project/doc/";
  1682. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1683. }
  1684. /**
  1685. * Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of project.
  1686. * Note: array weekWorkLoad and weekWorkLoadPerTask are reset and filled at each call.
  1687. *
  1688. * @param int $datestart First day of week (use dol_get_first_day to find this date)
  1689. * @param int $taskid Filter on a task id
  1690. * @param int $userid Time spent by a particular user
  1691. * @return int <0 if OK, >0 if KO
  1692. */
  1693. public function loadTimeSpent($datestart, $taskid = 0, $userid = 0)
  1694. {
  1695. $error = 0;
  1696. $this->weekWorkLoad = array();
  1697. $this->weekWorkLoadPerTask = array();
  1698. if (empty($datestart)) {
  1699. dol_print_error('', 'Error datestart parameter is empty');
  1700. }
  1701. $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task";
  1702. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
  1703. $sql .= " WHERE ptt.fk_task = pt.rowid";
  1704. $sql .= " AND pt.fk_projet = ".((int) $this->id);
  1705. $sql .= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' ";
  1706. $sql .= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'w') - 1)."')";
  1707. if ($taskid) {
  1708. $sql .= " AND ptt.fk_task=".((int) $taskid);
  1709. }
  1710. if (is_numeric($userid)) {
  1711. $sql .= " AND ptt.fk_user=".((int) $userid);
  1712. }
  1713. //print $sql;
  1714. $resql = $this->db->query($sql);
  1715. if ($resql) {
  1716. $daylareadyfound = array();
  1717. $num = $this->db->num_rows($resql);
  1718. $i = 0;
  1719. // Loop on each record found, so each couple (project id, task id)
  1720. while ($i < $num) {
  1721. $obj = $this->db->fetch_object($resql);
  1722. $day = $this->db->jdate($obj->task_date); // task_date is date without hours
  1723. if (empty($daylareadyfound[$day])) {
  1724. $this->weekWorkLoad[$day] = $obj->task_duration;
  1725. $this->weekWorkLoadPerTask[$day][$obj->fk_task] = $obj->task_duration;
  1726. } else {
  1727. $this->weekWorkLoad[$day] += $obj->task_duration;
  1728. $this->weekWorkLoadPerTask[$day][$obj->fk_task] += $obj->task_duration;
  1729. }
  1730. $daylareadyfound[$day] = 1;
  1731. $i++;
  1732. }
  1733. $this->db->free($resql);
  1734. return 1;
  1735. } else {
  1736. $this->error = "Error ".$this->db->lasterror();
  1737. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  1738. return -1;
  1739. }
  1740. }
  1741. /**
  1742. * Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of project.
  1743. * Note: array weekWorkLoad and weekWorkLoadPerTask are reset and filled at each call.
  1744. *
  1745. * @param int $datestart First day of week (use dol_get_first_day to find this date)
  1746. * @param int $taskid Filter on a task id
  1747. * @param int $userid Time spent by a particular user
  1748. * @return int <0 if OK, >0 if KO
  1749. */
  1750. public function loadTimeSpentMonth($datestart, $taskid = 0, $userid = 0)
  1751. {
  1752. $error = 0;
  1753. $this->monthWorkLoad = array();
  1754. $this->monthWorkLoadPerTask = array();
  1755. if (empty($datestart)) {
  1756. dol_print_error('', 'Error datestart parameter is empty');
  1757. }
  1758. $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task";
  1759. $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
  1760. $sql .= " WHERE ptt.fk_task = pt.rowid";
  1761. $sql .= " AND pt.fk_projet = ".((int) $this->id);
  1762. $sql .= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' ";
  1763. $sql .= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'm') - 1)."')";
  1764. if ($task_id) {
  1765. $sql .= " AND ptt.fk_task=".((int) $taskid);
  1766. }
  1767. if (is_numeric($userid)) {
  1768. $sql .= " AND ptt.fk_user=".((int) $userid);
  1769. }
  1770. //print $sql;
  1771. $resql = $this->db->query($sql);
  1772. if ($resql) {
  1773. $weekalreadyfound = array();
  1774. $num = $this->db->num_rows($resql);
  1775. $i = 0;
  1776. // Loop on each record found, so each couple (project id, task id)
  1777. while ($i < $num) {
  1778. $obj = $this->db->fetch_object($resql);
  1779. if (!empty($obj->task_date)) {
  1780. $date = explode('-', $obj->task_date);
  1781. $week_number = getWeekNumber($date[2], $date[1], $date[0]);
  1782. }
  1783. if (empty($weekalreadyfound[$week_number])) {
  1784. $this->monthWorkLoad[$week_number] = $obj->task_duration;
  1785. $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] = $obj->task_duration;
  1786. } else {
  1787. $this->monthWorkLoad[$week_number] += $obj->task_duration;
  1788. $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] += $obj->task_duration;
  1789. }
  1790. $weekalreadyfound[$week_number] = 1;
  1791. $i++;
  1792. }
  1793. $this->db->free($resql);
  1794. return 1;
  1795. } else {
  1796. $this->error = "Error ".$this->db->lasterror();
  1797. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  1798. return -1;
  1799. }
  1800. }
  1801. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1802. /**
  1803. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1804. *
  1805. * @param User $user Objet user
  1806. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  1807. */
  1808. public function load_board($user)
  1809. {
  1810. // phpcs:enable
  1811. global $conf, $langs;
  1812. // For external user, no check is done on company because readability is managed by public status of project and assignement.
  1813. //$socid=$user->socid;
  1814. $response = new WorkboardResponse();
  1815. $response->warning_delay = $conf->project->warning_delay / 60 / 60 / 24;
  1816. $response->label = $langs->trans("OpenedProjects");
  1817. $response->labelShort = $langs->trans("Opened");
  1818. $response->url = DOL_URL_ROOT.'/projet/list.php?search_project_user=-1&search_status=1&mainmenu=project';
  1819. $response->img = img_object('', "projectpub");
  1820. $response->nbtodo = 0;
  1821. $response->nbtodolate = 0;
  1822. $sql = "SELECT p.rowid, p.fk_statut as status, p.fk_opp_status, p.datee as datee";
  1823. $sql .= " FROM (".MAIN_DB_PREFIX."projet as p";
  1824. $sql .= ")";
  1825. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
  1826. // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
  1827. //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
  1828. $sql .= " WHERE p.fk_statut = 1";
  1829. $sql .= " AND p.entity IN (".getEntity('project').')';
  1830. $projectsListId = null;
  1831. if (!$user->rights->projet->all->lire) {
  1832. $response->url = DOL_URL_ROOT.'/projet/list.php?search_status=1&mainmenu=project';
  1833. $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
  1834. if (empty($projectsListId)) {
  1835. return $response;
  1836. }
  1837. $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  1838. }
  1839. // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
  1840. //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
  1841. // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
  1842. //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id).") OR (s.rowid IS NULL))";
  1843. //print $sql;
  1844. $resql = $this->db->query($sql);
  1845. if ($resql) {
  1846. $project_static = new Project($this->db);
  1847. // This assignment in condition is not a bug. It allows walking the results.
  1848. while ($obj = $this->db->fetch_object($resql)) {
  1849. $response->nbtodo++;
  1850. $project_static->statut = $obj->status;
  1851. $project_static->opp_status = $obj->fk_opp_status;
  1852. $project_static->date_end = $this->db->jdate($obj->datee);
  1853. if ($project_static->hasDelay()) {
  1854. $response->nbtodolate++;
  1855. }
  1856. }
  1857. return $response;
  1858. }
  1859. $this->error = $this->db->error();
  1860. return -1;
  1861. }
  1862. /**
  1863. * Function used to replace a thirdparty id with another one.
  1864. *
  1865. * @param DoliDB $db Database handler
  1866. * @param int $origin_id Old thirdparty id
  1867. * @param int $dest_id New thirdparty id
  1868. * @return bool
  1869. */
  1870. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1871. {
  1872. $tables = array(
  1873. 'projet'
  1874. );
  1875. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1876. }
  1877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1878. /**
  1879. * Charge indicateurs this->nb pour le tableau de bord
  1880. *
  1881. * @return int <0 if KO, >0 if OK
  1882. */
  1883. public function load_state_board()
  1884. {
  1885. // phpcs:enable
  1886. global $user;
  1887. $this->nb = array();
  1888. $sql = "SELECT count(p.rowid) as nb";
  1889. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  1890. $sql .= " WHERE";
  1891. $sql .= " p.entity IN (".getEntity('project').")";
  1892. if (empty($user->rights->projet->all->lire)) {
  1893. $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
  1894. $sql .= "AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  1895. }
  1896. $resql = $this->db->query($sql);
  1897. if ($resql) {
  1898. while ($obj = $this->db->fetch_object($resql)) {
  1899. $this->nb["projects"] = $obj->nb;
  1900. }
  1901. $this->db->free($resql);
  1902. return 1;
  1903. } else {
  1904. dol_print_error($this->db);
  1905. $this->error = $this->db->error();
  1906. return -1;
  1907. }
  1908. }
  1909. /**
  1910. * Is the project delayed?
  1911. *
  1912. * @return bool
  1913. */
  1914. public function hasDelay()
  1915. {
  1916. global $conf;
  1917. if (!($this->statut == self::STATUS_VALIDATED)) {
  1918. return false;
  1919. }
  1920. if (!$this->date_end) {
  1921. return false;
  1922. }
  1923. $now = dol_now();
  1924. return ($this->date_end) < ($now - $conf->project->warning_delay);
  1925. }
  1926. /**
  1927. * Charge les informations d'ordre info dans l'objet commande
  1928. *
  1929. * @param int $id Id of order
  1930. * @return void
  1931. */
  1932. public function info($id)
  1933. {
  1934. $sql = 'SELECT c.rowid, datec as datec, tms as datem,';
  1935. $sql .= ' date_close as datecloture,';
  1936. $sql .= ' fk_user_creat as fk_user_author, fk_user_close as fk_use_cloture';
  1937. $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as c';
  1938. $sql .= ' WHERE c.rowid = '.((int) $id);
  1939. $result = $this->db->query($sql);
  1940. if ($result) {
  1941. if ($this->db->num_rows($result)) {
  1942. $obj = $this->db->fetch_object($result);
  1943. $this->id = $obj->rowid;
  1944. if ($obj->fk_user_author) {
  1945. $cuser = new User($this->db);
  1946. $cuser->fetch($obj->fk_user_author);
  1947. $this->user_creation = $cuser;
  1948. }
  1949. if ($obj->fk_user_cloture) {
  1950. $cluser = new User($this->db);
  1951. $cluser->fetch($obj->fk_user_cloture);
  1952. $this->user_cloture = $cluser;
  1953. }
  1954. $this->date_creation = $this->db->jdate($obj->datec);
  1955. $this->date_modification = $this->db->jdate($obj->datem);
  1956. $this->date_cloture = $this->db->jdate($obj->datecloture);
  1957. }
  1958. $this->db->free($result);
  1959. } else {
  1960. dol_print_error($this->db);
  1961. }
  1962. }
  1963. /**
  1964. * Sets object to supplied categories.
  1965. *
  1966. * Deletes object from existing categories not supplied.
  1967. * Adds it to non existing supplied categories.
  1968. * Existing categories are left untouch.
  1969. *
  1970. * @param int[]|int $categories Category or categories IDs
  1971. * @return void
  1972. */
  1973. public function setCategories($categories)
  1974. {
  1975. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1976. return parent::setCategoriesCommon($categories, Categorie::TYPE_PROJECT);
  1977. }
  1978. /**
  1979. * Create an array of tasks of current project
  1980. *
  1981. * @param User $user Object user we want project allowed to
  1982. * @return int >0 if OK, <0 if KO
  1983. */
  1984. public function getLinesArray($user)
  1985. {
  1986. require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  1987. $taskstatic = new Task($this->db);
  1988. $this->lines = $taskstatic->getTasksArray(0, $user, $this->id, 0, 0);
  1989. }
  1990. }